O(n) Python Solution with Comments


  • 0
    J
    class Solution(object):
        def romanToInt(self, s):
            """
            :type s: str
            :rtype: int
            """
            # Conversion dictionary
            r_to_i = {'I': 1,
                      'V': 5,
                      'X': 10,
                      'L': 50,
                      'C': 100,
                      'D': 500,
                      'M': 1000}
            
            # Traverse the Roman numerals from right to left, 
            # Check if current numeral is smaller than previous.
            # If smaller, subtract current from the sum.
            # If greater, add current to the sum
            s = s[::-1]
            previous, current = r_to_i[s[0]], 0
            sum = previous
            for c in s[1:]:
                current = r_to_i[c]
                if current < previous:
                    sum -= current
                else:
                    sum += current
                previous = current
            return sum
    

Log in to reply
 

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