Another Python solution


  • 0
    A
    class Solution(object):
        def operate(self, op, numstack):
            nr = numstack.pop()
            nl = numstack.pop()
            if op == '+':
                res = int(nl) + int(nr)
            else:
                res = int(nl) - int(nr)
            numstack.append(res)
            return res
        
        def is_num(self, c):
            if c != ' ' and c != '+' and c != '-' and c != '(' and c != ')':
                return True
            else:
                return False
        
        def calculate(self, s):
            """
            :type s: str
            :rtype: int
            """
            opstack = []
            numstack = []
            res = None
            n = 0
            while n < len(s):
                i = s[n]
                if i != ' ':
                    if i == '+' or i == '-':
                        while len(opstack) > 0:
                            if opstack[-1] == '+' or opstack[-1] == '-':
                                op = opstack.pop()
                                self.operate(op, numstack)
                            else:
                                break;
                        opstack.append(i)
                    elif i == '(':
                        opstack.append(i)
                    elif i == ')':
                        op = opstack.pop()
                        while op != '(':
                            self.operate(op, numstack)
                            op = opstack.pop()
                    else:
                        num = int(i)
                        while n+1 < len(s) and self.is_num(s[n+1]):
                            i = s[n+1]
                            num = num*10 + int(i)
                            n = n+1
                        numstack.append(num)
                n = n+1
            while len(opstack) > 0:
                op = opstack.pop()
                res = self.operate(op, numstack)
            return numstack.pop()
    

Log in to reply
 

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