[
math
string
]
BinarySearch 0221 Roman Numeral to Integer
Problem statement
https://binarysearch.com/problems/Roman-Numeral-to-Integer/
Solution
Equal to Leetcode 0013. Roman to Integer.
Complexity
It is O(k)
for time and space, where k
is the length of s
.
Code
class Solution:
def solve(self, s):
dic = {"I":1, "V":5, "X":10, "L": 50, "C": 100, "D": 500, "M": 1000}
fix = {"IX": 2, "IV": 2, "XL": 20, "XC": 20, "CD": 200, "CM": 200}
ans = 0
for elem in s: ans += dic[elem]
for i, j in zip(s, s[1:]):
if i + j in fix: ans -= fix[i + j]
return ans