【leetcode系列】【py3】【中等】罗马数字转整数

题目:

【leetcode系列】【py3】【中等】罗马数字转整数

原题链接: https://leetcode-cn.com/problems/roman-to-integer/

 

解题思路:

建立映射表

遍历字符串的时候,先判断连续的两个字符是否在映射表中

如果在,则使用两个字符对应的数字

如果不在,则使用首个字符对应的数字,将第二个字符记录,作为下次循环的首字符

 

需要注意的是,如果循环完成后,保存的首字符不为空,需要特殊处理追加一下

 

代码实现:

class Solution:
    def romanToInt(self, s: str) -> int:
        if 0 == len(s):
            return 0

        str_map = {'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000, 'IV' : 4, 'IX' : 9, 'XL' : 40, 'XC' : 90, 'CD' : 400, 'CM' : 900}
        
        last_cha = s[0]
        ret_num = 0
        for curr_cha in s[1:]:
            tmp_str = last_cha + curr_cha
            
            if tmp_str in str_map and len(last_cha) > 0:
                ret_num += str_map[tmp_str]
                last_cha = ''
            elif len(last_cha) > 0:
                ret_num += str_map[last_cha]
                last_cha = curr_cha
            else:
                last_cha = curr_cha
                
        if len(last_cha) > 0:
            ret_num += str_map[last_cha]
            
        return ret_num