Simple Recursive version, Python


  • 0
    W

    in case be asked to implement recursive version

    class Solution(object):
        def romanToInt(self, s):
            """
            :type s: str
            :rtype: int
            """
            roman = {'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1}
            self.res = 0
            def dfs(idx, prev):
                if idx > len(s) - 1:
                    return
                curr = roman[s[idx]]
                if curr > prev and idx > 0:
                    self.res += curr - 2 * prev
                else:
                    self.res += curr
                dfs(idx + 1,  curr)
                
            dfs(0,  None)
            return self.res
    

Log in to reply
 

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