III is 1+1+1, not as 3.I before V), we subtract it. Otherwise, we add it.total starts at 0.s from left to right.i, compare the value of the current character s[i] with the value of the next character s[i+1].s[i] is smaller than s[i+1], subtract the value of s[i] from total.s[i] to total.i by 1, not two. Thus we are sliding size 2 window by 1 step.i reaches the end of the string s.total is the integer representation of the Roman numeral.class Solution:
def romanToInt(self, s: str) -> int:
roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
for i in range(len(s)):
if (i < len(s)-1) and (roman_map[s[i]] < roman_map[s[i+1]]):
total -= roman_map[s[i]]
else:
total += roman_map[s[i]]
return total