[LeetCode] 224. Basic Calculator @ python

一.题目:
实现一个基本的计算器,输入为包含"(",")","+","-"," "的字符串,输出运算结果.
二.解题思路:
这种题肯定是用栈实现,一般建立两个栈(数字栈和符号栈),有以下几种情况:
(1)对于数字,注意连续几位都是数字;
(2)对于符号,注意符号的优先级
代码如下:

class Solution(object):
    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        num_stack = []
        sign_stack = []
        for i in range(len(s)):
            if s[i].isdigit():
                if num_stack == []:
                    num_stack.append(int(s[i]))
                elif s[i-1].isdigit():
                    num_stack[-1] = 10*num_stack[-1]+int(s[i])
                else:
                    num_stack.append(int(s[i]))
                
            elif s[i] == " ":
                continue
                
            elif (s[i] == "+" or s[i] == "-"):
                if sign_stack == [] or sign_stack[-1] == "(":
                    sign_stack.append(s[i])
                else:
                    a = num_stack.pop()
                    b = num_stack.pop()
                    num_stack.append(b+a if sign_stack.pop() == "+" else b-a )
                    sign_stack.append(s[i])

            elif s[i] == "(":
                sign_stack.append(s[i])
            else:
                if sign_stack[-1] == "(":
                    sign_stack.pop()
                else:
                    a = num_stack.pop()
                    b = num_stack.pop()
                    num_stack.append(b+a if sign_stack.pop() == "+" else b-a )
                    sign_stack.pop()
        if len(num_stack) == 1:
            return num_stack[0]
        else:
            a = num_stack.pop()
            b = num_stack.pop()
            return b+a if sign_stack.pop() == "+" else b-a
上一篇:224. Basic Calculator


下一篇:实验一