classSolution(object):defromanToInt(self, s):"""
:type s: str
:rtype: int
"""# 双指针
s_list =list(s)
slow =0
fast =1
n =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 +=2
fast +=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 +=2
fast +=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 +=2
fast +=2if slow < n and fast >= n:
res += rom_map[s_list[slow]]else:
res += rom_map[s_list[slow]]
slow +=1
fast +=1if fast >= n:
res += rom_map[s_list[slow]]return res
2. 前面小于后面则减
classSolution(object):defromanToInt(self, s):"""
:type s: str
:rtype: int
"""
rom_map ={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
res =0
n =len(s)for i, ch inenumerate(s):
value = rom_map[ch]if i < n -1and value < rom_map[s[i +1]]:
res -= value
else:
res += value
return res