Leetcode_No.13 Roman to Integer

自己的解题思路:

  枚举出Roman字符的总数,包括单独的,与组合的(IV)这种的,然后从给出的字符串中统计出Roman字符的总数,计算出对应的Integer值

  刚刚开始使用for循环来遍历,后面改进用列表解析来算最后的总值

 

涉及到的python知识点:

  str的replace(s1,s2)用法:用""空字符替换到匹配到的Roman字符

  str的count(s)用法:统计s出现的总数

  列表解析

  sum()函数

 代码:

        str = s
        symbol_single_list = ["I","V","X","L","C","D","M"]
        symbol_single_dic = {'I':[1,0],'V':[5,0],'X':[10,0],'L':[50,0],'C':[100,0],'D':[500,0],'M':[1000,0]}
        symbol_mul_dic = {'IV':[4,0],'IX':[9,0],'XL':[40,0],'XC':[90,0],'CD':[400,0],'CM':[900,0]}
       
        for i in symbol_mul_dic.keys():
            if i in str:
                symbol_mul_dic[i][1] = str.count(i)
                str = str.replace(i,"")
               
           
        for i in symbol_single_dic.keys():
            if i in str:
                symbol_single_dic[i][1] = str.count(i)
                str = str.replace(i,"")

       
        total = sum([i[0]*i[1] for i in symbol_mul_dic.values()]) + sum([i[0]*i[1] for i in symbol_single_dic.values()])
           
        return total

   

 

上一篇:LeetCode-12. Integer to Roman


下一篇:12. Integer to Roman