# 0013. Roman to Integer ###### tags: `Leetcode` `Easy` `String` Link: https://leetcode.com/problems/roman-to-integer/description/ ## Code ### 思路一 ```python= class Solution: def romanToInt(self, s: str) -> int: roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} ans = 0 for i in range(len(s)-1): if roman[s[i]]<roman[s[i+1]]: ans -= roman[s[i]] else: ans += roman[s[i]] return ans + roman[s[-1]] ``` ### 思路二 ```python= class Solution: def romanToInt(self, s: str) -> int: roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} ans = 0 s = s.replace("IV", "IIII").replace("IX", "VIIII") s = s.replace("XL", "XXXX").replace("XC", "LXXXX") s = s.replace("CD", "CCCC").replace("CM", "DCCCC") for i in s: ans += roman[i] return ans ```