代码:
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dict1 = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
nums = 0
t = len(s)
i= 0
while i<t :
if s[i]=='I':
if i+1 == t:
nums+=dict1.get(s[i])
i+=1
else:
if s[i+1] =='V':
nums+=4
i+=2
elif s[i+1]=='X':
nums+=9
i+=2
else:
nums+=dict1.get(s[i])
i+=1
elif s[i]=='X':
if i+1 == t:
nums+=dict1.get(s[i])
i+=1
else:
if s[i+1] =='L':
nums+=40
i+=2
elif s[i+1]=='C':
nums+=90
i+=2
else:
nums+=dict1.get(s[i])
i+=1
elif s[i]=='C':
if i+1 == t:
nums+=dict1.get(s[i])
i+=1
else:
if s[i+1] =='D':
nums+=400
i+=2
elif s[i+1]=='M':
nums+=900
i+=2
else:
nums+=dict1.get(s[i])
i+=1
else:
nums+=dict1.get(s[i])
i+=1
return nums