码迷,mamicode.com
首页 > 其他好文 > 详细

Roman To Integer

时间:2016-05-05 00:22:49      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:

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
        

 

Roman To Integer

标签:

原文地址:http://www.cnblogs.com/sherylwang/p/5460077.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!