zoukankan      html  css  js  c++  java
  • [leetcode]13. Roman to Integer

    应该有比双循环更省时间的方法(in),可惜在客户现场网络不好,就用双循环做了。

    Success
    Details 
    Runtime: 96 ms, faster than 54.32% of Python3 online submissions forRoman to Integer.
    Memory Usage: 13.4 MB, less than 37.41% of Python3 online submissions for Roman to Integer.
     

    Submission Detail

    3999 / 3999 test cases passed.
    Status: 

    Accepted

    Runtime: 96 ms
    Memory Usage: 13.4 MB
    Submitted: 1 minute ago
     
    class Solution:
        def romanToInt(self, s: str) -> int:
            romanDict1 = {"CM":900, "CD":400,"XC":90, "XL":40,"IX":9,"IV":4}
            romanList1 = ["CM", "CD","XC", "XL","IX","IV"]
            romanDict2 = {"M": 1000, "D": 500, "C": 100, "L": 50, "X": 10,"V": 5, "I": 1}
            romanList2 = ["M", "D", "C", "L", "X","V", "I"]
            sum =0
            for index in range(len(s) -1):
                for item in range(len(romanList1)):
                    if s[index:index +2] ==romanList1[item]:
                        sum += romanDict1[romanList1[item]]
                        s = s[:index] +'00'+ s[index+2:]
    
            for index in range(len(s)):
                for item in range(len(romanList2)):
                    if s[index] ==romanList2[item]:
                        sum += romanDict2[romanList2[item]]
                        s = s[:index] +'0'+ s[index+1:]
            return sum

     48ms:

    class Solution:
        def romanToInt(self, s: str) -> int:
            RomanDictionary = {"I":1,"V":5, "X":10,"L":50,"C":100,"D":500,"M":1000}
            s = s.replace("IV", "IIII").replace("IX", "VIIII")
            s = s.replace("XL", "XXXX").replace("XC", "LXXXX")
            s = s.replace("CD", "CCCC").replace("CM", "DCCCC")
            Sum = 0
            for Character in s:
                Sum = Sum + RomanDictionary[Character]
            return Sum
  • 相关阅读:
    大数减法
    MySQL配置的一些坑
    最大流_Edmonds-Karp算法
    最小生成树两连
    最短路三连
    对拍
    Broadcast
    Intent
    Custom Views
    Fragment
  • 原文地址:https://www.cnblogs.com/alfredsun/p/10871512.html
Copyright © 2011-2022 走看看