考虑三种特殊情况即可:
class Solution:
def romanToInt(self, s: str) -> int:
tap=dict([('I',1),('V',5),('X',10),('L',50),('C',100),('D',500),('M',1000)])
sum=0
for i in range(len(s)-1):
if (s[i]=='I' and s[i+1]=='V') or (s[i]=='I' and s[i+1]=='X'):
box=-tap['I']
sum+=box
elif (s[i]=='X' and s[i+1]=='L') or (s[i]=='X' and s[i+1]=='C'):
box=-tap['X']
sum+=box
elif (s[i]=='C' and s[i+1]=='D') or (s[i]=='C' and s[i+1]=='M'):
box=-tap['C']
sum+=box
else:
sum+=tap[s[i]]
return sum+tap[s[-1]]