13. Roman to Integer

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.


Strings in Python are immutable (can't be changed). Because of this, the effect of line.replace(...) is just to create a new string, rather than changing the old one. You need to rebind (assign) it to line in order to have that variable take the new value, with those characters removed.

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        roman = {'I':1, 'V':5, 'X':10,'L':50,'C':100,'D':500,'M':1000}
        sub = {'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
        ans = 0
        ss = [s]
        for key in sub:
            if key in s:
                ans += sub[key]
                new = ss.pop()
                ss.append(new.replace(key, ''))
        sss = ss.pop()
        for c in sss:
            ans += roman[c]
        return ans
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容