leetcode 224. 基本计算器 python

使用栈的栈(准确地说是双向队列的双向队列)。记录一下

class Solution(object):
    def calculate(self, s):
        def add(x,y):
            return x+y
        def minus(x,y):
            return x-y
        outer_stack=[]
        inner_stack=[]
        num=None
        for c in s:
            if c.isdigit():
                num = 0 if num is None else num
                num = 10 * num + int(c)
                continue
            if c=='(':
                if inner_stack!='':
                    outer_stack.append(inner_stack)
                inner_stack=[]
                continue
            if c=='+':
                if num is not None:
                    inner_stack.append(num)
                num=None
                inner_stack.append(add)
                if len(inner_stack)>=3:
                    x=inner_stack.pop(0)
                    ope=inner_stack.pop(0)
                    y=inner_stack.pop(0)
                    inner_stack.insert(0,ope(x,y))
                continue
            if c=='-':
                if num is not None:
                    inner_stack.append(num)
                num=None
                inner_stack.append(minus)
                if len(inner_stack)>=3:
                    x=inner_stack.pop(0)
                    ope=inner_stack.pop(0)
                    y=inner_stack.pop(0)
                    inner_stack.insert(0,ope(x,y))
            if c==')':
                if num is not None:
                    inner_stack.append(num)
                num=None                
                x=inner_stack.pop(0)
                while len(inner_stack)>0:
                    ope=inner_stack.pop(0)
                    y=inner_stack.pop(0)
                    x=ope(x,y)
                if len(outer_stack)>0:
                    inner_stack=outer_stack.pop()
                    inner_stack.append(x)
        if num is not None:
            inner_stack.append(num)
        while len(inner_stack)>0 or len(outer_stack)>0:
            x=inner_stack.pop(0)
            while len(inner_stack)>0:
                ope=inner_stack.pop(0)
                y=inner_stack.pop(0)
                x=ope(x,y)
            if len(outer_stack)>0:
                inner_stack=outer_stack.pop()
                inner_stack.append(x)
        return x

你可能感兴趣的:(leetcode 224. 基本计算器 python)