leeocde 04 罗马数字转换整数

class Solution:
    def romanToInt(self,s:str) -> int:
        d = {'I':1,'IV':3,'V':5,'IX':8,'X':10,'XL':30,'L':50,'XC':80,'C':100,'CD':300,'D':500,'CM':800,'M':1000}
        result = 0
        for i,n in enumerate(s):
            a = max(i-1,0)
            b = i + 1
            str1 = s[a:b]
            if str1 in d:
                c = d.get(str1)
                result += c
            else:
                e = d[n]
                result += e
        return result

if __name__ == '__main__':
    a = Solution()
    s = 'MCMXCIV'
    b = a.romanToInt(s)
    print(b)

你可能感兴趣的:(leecode,leetcode,算法,职场和发展)