力扣13罗马数字转整数(简单)python3

在这里插入图片描述
解题思路:
判断所有的’I’、‘X’、‘C’的右边字符是否为特殊规则,若为特殊规则则减去罗马字符相对应的数字,若为正常规则则加上该罗马字符对应的数字。

class Solution:
    def romanToInt(self, s: str) -> int:
        num_dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        result = 0
        for index, i in enumerate(s):
            
            if i == 'I' and index < len(s) - 1 and s[index + 1] in ('V', 'X'):
                result -= num_dict[i]
            elif i == 'X' and index < len(s) - 1 and s[index + 1] in ('L', 'C'):
                result -= num_dict[i]
            elif i == 'C' and index < len(s) - 1 and s[index + 1] in ('D', 'M'):
                result -= num_dict[i]
            else:
                result += num_dict[i]
        return result
class Solution:
    def romanToInt(self, s: str) -> int:
        num_dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        result = 0
        for index, i in enumerate(s):
            
            if index < len(s) -1 and s[index] < s[index + 1]:
                result -= num_dict[i]
            else:
                result += num_dict[i]
        return result

大神解题:
将所有特殊规则的形式加入字典中,没两个字符进行一个组合查找,若符合特殊规则(在字典里)则将字典中对应的数值相加,若是正常的规则则直接加对应的罗马字符对应的数字。
注:dict.get(key, default_value)

def romanToInt(self, s: str) -> int:
    d = {'I': 1, 'IV': 3, 'V': 5, 'IX': 8, 'X': 10, 'XL': 30, 'L': 50, 'XC': 80, 'C': 100, 'CD': 300, 'D': 500,
         'CM': 800, 'M': 1000}
    return sum(d.get(s[max(i - 1, 0):i + 1], d[n]) for i, n in enumerate(s))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值