Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
O(n) time go through the whole string. O(1) space.
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
ROMAN_HASH = {
'M' : 1000,
'D' : 500,
'C' : 100,
'L' : 50,
'X' : 10,
'V' : 5,
'I' : 1
}
total_value = 0
previous_value = 0
for char in s:
current_value = ROMAN_HASH[char]
if previous_value < current_value:
total_value += current_value - 2 * previous_value
else:
total_value += current_value
previous_value = current_value
return total_value

本文介绍了一种将罗马数字转换为整数的算法实现,该算法通过一次遍历输入字符串来完成转换,并确保了时间和空间复杂度的有效控制。

被折叠的 条评论
为什么被折叠?



