Python with stack


  • 7
    Z

    This solution uses stack to store previous result and sign when encounter a "("

    For this problem storing sign is enough, and will be faster.

    def calculate(self, s):
        res, num, sign, stack = 0, 0, 1, [1]
        for i in s+"+":
            if i.isdigit():
                num = 10*num + int(i)
            elif i in "+-":
                res += num * sign * stack[-1]
                sign = 1 if i=="+" else -1
                num = 0
            elif i == "(":
                stack.append(sign * stack[-1])
                sign = 1
            elif i == ")":
                res += num * sign * stack[-1]
                num = 0
                stack.pop()
        return res
    

  • 0

    If you are able to code something like this at an interview, you're God!


  • 0
    Z

    I have seen this problem in an interview. Code does not need to be very clean, but the idea should be there.


Log in to reply
 

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