【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