Roman To Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

这题比Integer To Roman简单很多,主要是考虑有没有左减的存在。实际觉得leetcode的规则要简单于罗马数字本身的规则,即左减数字只能为I、X、C,且不能跨位。比较简单的思路是每位值都加上,每次考虑前一位是不是符合左减条件,符合则减去2倍的值。时间复杂度O(n),空间复杂度O(1),代码如下: 

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0
        map = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
        ret = map[s[0]]
        for i in xrange(1,len(s)):
            val = map[s[i]]
            ret += val 
            if  val > map[s[i-1]]:
                ret -= 2*map[s[i-1]]
        return ret
        

 

转载于:https://www.cnblogs.com/sherylwang/p/5460077.html

你可能感兴趣的:(Roman To Integer)