Simple python solution with dict


  • 1
    G

    Simply python solution run in 152 ms

       def romanToInt(self, s):
            ROMAN_MAP = {
                'M': 1000,
                'D': 500,
                'C': 100,
                'L': 50,
                'X': 10,
                'V': 5,
                'I': 1
            }
            
            total = 0
            prev = 0
            for i in range(len(s)):
                curr = ROMAN_MAP[s[i]]
                if curr > prev:
                    total += curr - 2 * prev
                else:
                    total += curr
                prev = curr
            return total

  • 0
    G

    ah it can be improved a bit to:

    total += curr
    if curr > prev:
        total -= 2 * prev

  • 0
    A
    This post is deleted!

  • 0
    R

    it can be in less code:

       mappedS = [ROMAN_MAP[x] for x in s]     
       total= sum(mappedS)
       for index in range(len(mappedS) - 1):
            if mappedS[index] < mappedS[index+1]:
                total -= 2 * mappedS[index]

Log in to reply
 

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