利用规律,一般而言,罗马数字的字符是从大到小排列的,特殊的如IV=4=-1+5,所以扫描每个字符,如果该字符比后一个字符大,则加上对应的数,如果比后一个字符小,则减去对应的数,注意i从0到l-2,l-1在for循环外单独处理。

class Solution:
    def romanToInt(self, s: str) -> int:
        hash_map = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
        num = 0 
        for i in range(len(s)-1):
            if hash_map[s[i]] >= hash_map[s[i+1]]:
                num += hash_map[s[i]]
            else:
                 num -= hash_map[s[i]]
        num += hash_map[s[-1]]
        return num