Fool-proof Python Solution with O(n) time


  • 0
    L
    class Solution(object):
        def romanToInt(self, s):
            """
            :type s: str
            :rtype: int
            """
            
            # consider string composed of pre + post
            # pre is the number to be deducted form sum, post is to be added to sum
            # use a dict to save reference of roman - arabic conversion for basic roman digits
            # at any index where dict[i] < dict[i + 1], add that number to pre,
            # otherwise add that number to post,
            # eventually, return sum = post - pre
            
            romanDict = {
                'I': 1,
                'V': 5,
                'X': 10,
                'L': 50,
                'C': 100,
                'D': 500,
                'M': 1000
            }
            
            pre = 0
            post = 0
    
            digits = list(s.upper()) # Make sure input all upper case
                    
            for i in range(0, len(digits)):
                if (i < len(digits) - 1) and (romanDict[digits[i]] < romanDict[digits[i + 1]]):
                    pre += romanDict[digits[i]]
                else:
                    post += romanDict[digits[i]]
            
            return post - pre

  • 0
    N

    Why do you need two variables for this? Why not just add and subtract from a total and then return that?


Log in to reply
 

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