Python solution


  • 0
    Y
    def calculate(self, s):
        ss = []
        i, l, coe = 0, len(s), 1
        while i < l:
            if s[i].isdigit():
                b = i
                i+=1
                while i < l and s[i].isdigit(): i+=1
                ss.append( coe*int(s[b:i]) )
                continue
            if s[i] in "()":
                if s[i] == "(" and coe == -1: ss.append("-")
                ss.append(s[i])
                coe = 1
            elif s[i] == "+": coe = 1
            elif s[i] == "-": coe = -1 
            i += 1
        stack = []
        while ss:
            cur = ss.pop()
            if cur == "(":
                num = 0
                t = stack.pop()
                while not t == ")":
                    num += t
                    t = stack.pop()
                if ss and ss[-1] == "-": 
                    num*=-1
                    ss.pop()
                stack.append(num)
            else: stack.append(cur)
        return reduce(lambda x, y: x+y, stack)

Log in to reply
 

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