class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
number=0
next=False
dict1={'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1,}
dict2={'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
for i in range(len(s)):
if next:
next=False
continue
if s[i] in ('M','D','L','V'):
number=number+dict1[s[i]]
if s[i] in ('I','X','C'):
if i!=(len(s)-1) and s[i:i+2] in dict2:
number=number+dict2[s[i:i+2]]
next=True
else:
number=number+dict1[s[i]]
return number
重点:
- 当I/X/C在大符号之前,计算完需跳过下一次循环
- 使用字典
后来看评论里大家的讨论,发现还有一种想法更清晰:
首先建立一个HashMap来映射符号和值,然后对字符串从左到右来,如果当前字符代表的值不小于其右边,就加上该值;否则就减去该值。以此类推到最后,最终得到的结果即是答案
网友评论