class Solution:
def romanToInt(self, s: str) -> int:
chars = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV','I']
nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
map_ = dict((k, v) for k,v in zip(chars, nums))
# 字符串长度
n = len(s)
# 结果变量
res = 0
# 开始循环
i = 0
while i < n:
# 判断两个字符
if i+1 < n and s[i:i+2] in map_:
# print(s[i:i+2], ':', map_[s[i:i+2]])
res += map_[s[i:i+2]]
i += 2
else:
res += map_[s[i]]
# print(s[i], ':', map_[s[i]])
i += 1
return res
class Solution:
def romanToInt(self, s: str) -> int:
chars = ['M', 'D', 'C', 'L', 'X', 'V','I']
nums = [1000, 500, 100, 50, 10, 5, 1]
map_ = dict((k, v) for k,v in zip(chars, nums))
# 字符串长度
n = len(s)
# 结果变量
res = 0
# 开始循环
i = 0
pre_num = map_[s[i]]
for i in range(n):
cur_num = map_[s[i]]
if pre_num < cur_num:
# print('-', pre_num)
res -= 2*pre_num
res += cur_num
# print('+', cur_num)
pre_num = cur_num
return res
干饭完毕,无浪费