my Python solution beats 99.4%


  • 0
    Z

    Not very clean, try several times to get its performance better, stop trying here.
    The idea is capture two numbers each time, if the back one is larger, these two numbers are a group, and the sum of this little group is (back - front), if not, just add the front number and leave the back one to the next loop.

    If there is any suggestion about my solution, please let me know. :D

    class Solution(object):
        def romanToInt(self, s):
            """
            :type s: str
            :rtype: int
            """
            dic = {'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1}
            total = 0
            idx = 0
            num2 = 0
            while idx < len(s):
                if idx+1 == len(s):
                    return total + dic[s[idx]]
                # num1 is front number, if in the last loop num2 is not taken account, it will be num1 this time
                num1 = dic[s[idx]] if not num2 else num2
                # num2 is back number
                num2 = dic[s[idx+1]] 
                if num1 < num2:
                    total += num2 - num1
                    # if num2 is taken account, make it 0 to let next loop know
                    num2 = 0
                    idx += 1
                else:
                    total += num1
                idx += 1
            return total    
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.