Leetcode每日一题2021.2.25第13题:罗马数字转整数

题目描述

在这里插入图片描述

示例

在这里插入图片描述

思路

通过观察,我们发现:两个字符中,

  • 左字符 < 右字符时,= 右边的字符数 - 左边的字符数
  • 左字符 >= 右字符时,= 右边的字符数 + 左边的字符数

算法

我们将对应关系用 {字符:数值}的形式存在 Roman2Int 的哈希表中,然后从左到右遍历每个字符,如果 s[i] < s[i+1] ,就将结果减去 s[i] 代表的数字;否则,将结果加上 s[i] 代表的数字。并且最后一个字符代表的数字是一定得加在结果里的。

代码

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

猜你喜欢

转载自blog.csdn.net/m0_51210480/article/details/114093263
今日推荐