Skip to main content

13. Roman to Integer

https://leetcode.com/problems/roman-to-integer/

Python

class Solution:
def romanToInt(self, s: str) -> int:
mapper = {
"I": 1, "V": 5, "X": 10,
"L": 50, "C": 100, "D": 500,
"M": 1000,
}

if len(s) == 1:
return mapper[s]

symbols = list(s)
ans, i = 0, len(s)-1
while i >= 0:
cur = mapper[symbols[i]]
j = i-1
while mapper[symbols[j]] < mapper[symbols[i]] and j >= 0:
cur -= mapper[symbols[j]]
j -= 1

ans += cur
i = j
return ans