leetcode python 罗马数字转整数 【简单题】

1. 读懂题目

注意: 提示中已明确,不会出现跨位的情况。所以是可以简化为左右数字的加减问题。

2. 分析,推导解法,产生思路。

解题思路:(1)字符转换为数字的问题。可使用列表list或字典dict,利用对应关系解题。

(2)对数字出现的问题,考虑左边小于右边则采用减法,左边大于右边则采用加法。

3. 代码实现

map_dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        sum = 0
        # 下标法/迭代器 遍历字符串
        i = 1
        print(len(s))
        while(i < len(s)):
            if (s[i-1] == 'I' and (s[i] == 'V'or s[i] == 'X')) or (s[i-1] == 'X' and (s[i] == 'L'or s[i] == 'C')) or (s[i-1] == 'C' and (s[i] == 'D'or s[i] == 'M')) :
                sum += map_dic[s[i]] - map_dic[s[i-1]]
                i = i+2
            else:
                sum += map_dic[s[i-1]]
                i = i +1
        if i < len(s)+1:
            sum += map_dic[s[i-1]]
        return sum

之前没有注意到,没有跨位的情况。下面为优化后的代码。

    def romanToInt1(self, s):   # 利用字典的下标,简化
        sum = 0
        for i in range(len(s)-1):
            if map_dic[s[i]] < map_dic[s[i+1]]:

                sum -= map_dic[s[i]]
                print(map_dic[s[i]], map_dic[s[i + 1]], sum)
            else:
                sum += map_dic[s[i]]
        sum += map_dic[s[-1]]
        return sum

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值