LeetCode-13(罗马数字转整数)(Python)

image.png

image.png
解法一(112 ms 93.86%):
class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}

        res=0
        for i in range(len(s)):
            if i+1<len(s) and s[i]=='I' and (s[i+1]=='V' or s[i+1]=='X'):
                res-=2
            if i+1<len(s) and s[i]=='X' and (s[i+1]=='L' or s[i+1]=='C'):
                res-=20
            if i+1<len(s) and s[i]=='C' and (s[i+1]=='D' or s[i+1]=='M'):
                res-=200
            res+=dic[s[i]]
        return res
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容