Recursive and easy python solution


  • 0
    J
    class Solution(object):
    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        x, y = self.cal(s, 0)
        return x
        
    def cal(self, s, i):
        num, result, sign = 0, 0, True # True: '+'
        while i < len(s):
            if s[i].isdigit():
                while i < len(s) and s[i].isdigit():
                    num = num * 10 + int(s[i])
                    i += 1
                result += (-num, num)[sign]
                num = 0
                continue
            else:
                if s[i] == '(':
                    x, y = self.cal(s, i+1)
                    result += (-x, x)[sign]
                    i = y
                elif s[i] == ')':
                    break
                elif s[i] in "+-":
                    sign = s[i] == '+'
            i += 1
    
        return result, i
    

    The cal calculates z + ((x) - (y)) in the way that res + z + cal(x) - cal(y) -> res + cal(x) - cal(y) -> res + cal(y) -> res, where x, y and z stand for expressions.

    Once we've got a new operand, we calculate it immediately with recently updated operation and store the result in result.


Log in to reply
 

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