解题思路:
判断所有的’I’、‘X’、‘C’的右边字符是否为特殊规则,若为特殊规则则减去罗马字符相对应的数字,若为正常规则则加上该罗马字符对应的数字。
class Solution:
def romanToInt(self, s: str) -> int:
num_dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
result = 0
for index, i in enumerate(s):
if i == 'I' and index < len(s) - 1 and s[index + 1] in ('V', 'X'):
result -= num_dict[i]
elif i == 'X' and index < len(s) - 1 and s[index + 1] in ('L', 'C'):
result -= num_dict[i]
elif i == 'C' and index < len(s) - 1 and s[index + 1] in ('D', 'M'):
result -= num_dict[i]
else:
result += num_dict[i]
return result
class Solution:
def romanToInt(self, s: str) -> int:
num_dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
result = 0
for index, i in enumerate(s):
if index < len(s) -1 and s[index] < s[index + 1]:
result -= num_dict[i]
else:
result += num_dict[i]
return result
大神解题:
将所有特殊规则的形式加入字典中,没两个字符进行一个组合查找,若符合特殊规则(在字典里)则将字典中对应的数值相加,若是正常的规则则直接加对应的罗马字符对应的数字。
注:dict.get(key, default_value)
def romanToInt(self, s: str) -> int:
d = {'I': 1, 'IV': 3, 'V': 5, 'IX': 8, 'X': 10, 'XL': 30, 'L': 50, 'XC': 80, 'C': 100, 'CD': 300, 'D': 500,
'CM': 800, 'M': 1000}
return sum(d.get(s[max(i - 1, 0):i + 1], d[n]) for i, n in enumerate(s))