美文网首页
13. Roman to Integer

13. Roman to Integer

作者: 冷殇弦 | 来源:发表于2017-09-29 04:51 被阅读0次

    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
    

    相关文章

      网友评论

          本文标题:13. Roman to Integer

          本文链接:https://www.haomeiwen.com/subject/nsybextx.html