当前位置: 首页 > backend >正文

【leetcode】13. 罗马数字转整数

文章目录

    • 题目
    • 题解
      • 1. 枚举,双指针
      • 2. 前面小于后面则减

题目

13. 罗马数字转整数

在这里插入图片描述

题解

1. 枚举,双指针

class Solution(object):def romanToInt(self, s):""":type s: str:rtype: int"""# 双指针s_list = list(s)slow = 0 fast = 1n = len(s)rom_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}res = 0if n == 1:return rom_map[s_list[0]]while fast < n:if s_list[slow] in ['I'] and s_list[fast] in ['V', 'X']:res += rom_map[s_list[fast]] - rom_map[s_list[slow]]slow += 2fast += 2if slow < n and fast >= n:res += rom_map[s_list[slow]]elif s_list[slow] in ['X'] and s_list[fast] in ['L', 'C']:res += rom_map[s_list[fast]] - rom_map[s_list[slow]]slow += 2fast += 2if slow < n and fast >= n:res += rom_map[s_list[slow]]elif s_list[slow] in ['C'] and s_list[fast] in ['D', 'M']:res += rom_map[s_list[fast]] - rom_map[s_list[slow]]slow += 2fast += 2if slow < n and fast >= n:res += rom_map[s_list[slow]]else:res += rom_map[s_list[slow]]slow += 1fast += 1if fast >= n:res += rom_map[s_list[slow]]return res

2. 前面小于后面则减

class Solution(object):def romanToInt(self, s):""":type s: str:rtype: int"""rom_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}res = 0n = len(s)for i, ch in enumerate(s):value = rom_map[ch]if i < n - 1 and value < rom_map[s[i + 1]]:res -= valueelse:res += valuereturn res
http://www.xdnf.cn/news/17985.html

相关文章:

  • python学习DAY43打卡
  • MySQL 的 DDL / DML / DQL / DCL 做一次系统梳理:概念区别→常用语法→特点与注意点→实战小例子→常见面试/坑点速记
  • redis的key过期删除策略和内存淘汰机制
  • JavaWeb开发_Day14
  • Python虚拟环境与包管理工具(uv、Conda)
  • 发文暴论!线性注意力is all you need!
  • 【LeetCode每日一题】
  • Python---异常链(Exception Chaining)
  • sharding-jdbc读写分离配置
  • Spring——关于Bean以及自动配置
  • FTP上传文件错误
  • BM25算法和传统的TF-IDF算法的区别
  • IEEEtaes.cls解析
  • Trae中`settings.json`文件的Java配置项功能详解(二)
  • 343整数拆分
  • 双椒派E2000D开发板LED驱动开发实战指南
  • 随机整数列表处理:偶数索引降序排序
  • 杂记 03
  • 软件需求工程详解
  • 【自用】JavaSE--特殊文件Properties与XML、日志技术
  • 项目管理进阶——解读大型IT系统集成项目实施要点培训【附全文阅读】
  • 主从复制+哨兵
  • GPFS集群性能压测
  • MySQL的下载安装(MSI和ZIP版本都有)
  • Linux上配置环境变量
  • UDP/TCP套接字编程简单实战指南
  • 【总结型】c语言中的位运算
  • Hugging Face 与 NLP
  • Express开发快速学习
  • Spring Cloud系列—Alibaba Seata分布式事务