【Leetcode】【python】Roman to Integer 罗马数字转整数

题目大意

将罗马数字转为整数

解题思路

上一题不同,这一题可以使用dict。

来自:Gitbook

根据罗马数字的规则,只有在前面的字母比当前字母小的情况下要执行减法,其他情况只需要把罗马字母对应的数字直接相加即可。如果发现前一个字母比当前字母小,就减去前一个字母,因为错误的把它加入了结果,且在加上当前字母时还要减去前一个字母的值。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
table = {'M':1000, 'CM':900, 'D':500, 'CD':400, 'C':100, 'XC':90, 'L':50, 'XL': 40, 'X':10, 'IX':9, 'V':5, 'VI':4, 'I':1}
result = 0
for i in range(len(s)):
if i > 0 and table[s[i]] > table[s[i-1]]:
result += table[s[i]]
result -= 2 * table[s[i-1]]
else:
result += table[s[i]]
return result

总结