Plain simple solution (readability counts!)


  • 0
    I

    At first, map each one and two-character long substrings into its number. Then, search for a two-character long substring, and if you don't find it, try the one-character long substring.

    class Solution(object):
        mapping = {
            'I': 1, 'IV': 4, 'V': 5, 'IX': 9,
            'X': 10, 'XL': 40, 'L': 50, 'XC': 90,
            'C': 100, 'CD': 400, 'D': 500, 'CM': 900,
            'M': 1000,
        }
        
        def romanToInt(self, s):
            
            """
            :type s: str
            :rtype: int
            """
            mapping = self.mapping
            number, i = 0, 0
            while i < len(s):
                two = s[i: i + 2]
                if two in mapping:
                    number += mapping[two]
                    i += 2
                else:
                    one = s[i]
                    number += mapping[one]
                    i += 1
            return number
    

    This solution is much more readable than the other ones I found. It's efficient too, beating 99.62 % of python submissions (109 ms).


Log in to reply
 

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