题目链接:
https://leetcode-cn.com/problems/roman-to-integer/description/
代码:
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
s=s.replace('IV','Q').replace('IX','W').replace('XL','E').replace('XC','R').replace('CD','T').replace('CM','Y')
num = 0
dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, 'Q': 4, 'W': 9,
'E': 40, 'R': 90, 'T': 400, 'Y': 900}
for i in s:
num += dict[i]
return num
其实上述代码遇到一些不合法输入时并不严谨,但是题目的测试用例输入都是合法的。