AC Python Solution


  • 5
    T
    class Solution:
    def calculate(self, s):
        s = '+(+' + s + ')'
        s = s.replace('+-', '-').replace('++', '+') # for the corner case '-5', '+5'
        stack = []
        for i in s:
            if i == ')':
                total = 0
                while stack[-1] != '(':
                    total += int(stack.pop())
                stack.pop()
                sign = 1 if stack.pop() == '+' else -1
                stack.append(sign * total)
            elif i.isdigit() and stack[-1][-1] in '+-0123456789':
                stack[-1] += i
            elif i != ' ':
                stack.append(i)
        return stack[0]

  • 2
    X

    Brilliant solution, but there is a corner case that you may have missed. Try '-5'


  • 0
    T

    You are right, I add s = s.replace('+-', '-').replace('++', '+') for that corner case


  • 0
    J

    So glad I found this. Orders of magnitude faster than my solution. But the code does not accommodate for cases in which multiple opening parentheses are adjacent to one another other: '((1 + 2))' or '((1 + 2) + 3 + 4) + 5'. Granted the adjacent opening parentheses do not affect the computational result, they still make for a valid expression and may come in handy if we want to extend the code to also handle multiplications (e.g. '((1 + 2)3 + 4)5').

    An additional case in the for loop solves the issue:

                elif i == '(' and stack[-1] == '(':
                    stack.append('+')
                    stack.append(i)

Log in to reply
 

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