題目描述

description.png
思路:把所有字符相加,再單獨把前一位比后一位小的拿出來,減去2倍差值即可。
先建立一個dict,然后n>0時相減
class Solution:
def romanToInt(self, s: str) -> int:
dict={'I':1,'V':5,'X':10,'L':50,
'C':100,'D':500,'M':1000,}
result = 0
for n in range(len(s)):
if n>0 and dict[s[n]] > dict[s[n-1]]:
result = result + dict[s[n]]-2*dict[s[n-1]]
else:
result = result + dict[s[n]]
return result