Solution 1
class Solution:
def romanToInt(self, s: str) -> int:
number_map, ans = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M': 1000}, 0
for i in range(len(s)):
if i > 0 and number_map[s[i]] > number_map[s[i-1]]:
ans += number_map[s[i]] - 2*number_map[s[i-1]]
else: ans += number_map[s[i]]
return ans
Time complexity is O(n). Space complexity is O(1).