Python solution using REGEXP and stack, pretty clean code


  • 0
    class Solution(object):
        def calculate(self, s):
    
            def basic_calculator(s):
                def collapse_stack(num_stack, op_stack):
                    ops, nums, c = [], [], 1
                    while op_stack:
                        op = op_stack.pop()
                        if op == "(":
                            break
                        ops.append(op)
                        c += 1
                    while c:
                        nums.append(num_stack.pop())
                        c -= 1
                        
                    while len(nums) >= 2 and ops:
                        op = ops.pop()
                        a, b = nums.pop(), nums.pop()
                        nums.append(a + b if op == "+" else a - b)
                    num_stack.append(nums[-1])
                        
                
                op_stack, num_stack, res_int, n = [], [], 0, len(s)
                for i in range(n):
                    if s[i] in '(+-':
                        op_stack.append(s[i])
                    elif s[i] not in ')':
                        num_stack.append(int(s[i]))
                    if s[i] == ")":
                        collapse_stack(num_stack, op_stack)
                    
                collapse_stack(num_stack, op_stack)
                return 0 if not len(num_stack) else num_stack[0]
            
    
            l = re.findall(r'(\(|\)|\+|\-|[0-9]+)', s)
            return basic_calculator(l)

Log in to reply
 

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