Easy to understand Python solution with Stack


  • 1
    P
    class Solution(object):
        def calculate(self, s):
            """
            :type s: str
            :rtype: int
            """
            # stack stores previous result and sign
            stack, result = [], 0
            num, sign = '', 1
            for c in s + '+':
                if c != ' ':
                    if c in '+-':
                        result += int(num) * sign
                        sign = 1 if c == '+' else -1
                        num = ''
                    # put previous result and sign at (
                    elif c == '(':
                        stack.append(result)
                        stack.append(sign)
                        result, sign = 0, 1
                    # let previous result be result again
                    # let previous sign be sign again
                    # let result from within parenthese be num
                    elif c == ')':
                        result += int(num) * sign
                        num = str(result)
                        sign = stack.pop()
                        result = stack.pop()
                    else:
                        num += c
            return result
    

    stack is used to record previous result and previous sign. Hope it helps.


Log in to reply
 

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