【leetcode】224. Basic Calculator
题目如下:
解题思路:我的解法是使用两个栈,一个保存运算符,一个保存括号和数字。因为只有加减操作,所以每个数字入栈前,先判断栈顶是否是'(',如果不是,则该数字和栈顶的数字进行运算后,把原来栈顶的数字删掉,把计算的结果入栈;否则,直接入栈。如果遇到')',计算栈中所有的数字,直到遇到'('。考虑到几种特殊的输入,我在代码中做了一些优化:
1.输入只有一个数字,例如obj.calculate("1") -> 把输入字符串前后分别加上"("和")";
2.第一个运算数字是负数,例如例如obj.calculate("-2+1") -> 变成 ("0-2+1");
代码如下:
class Solution(object): #check if need to calculate before insert a new num to stack def calc(self,sk,op,num): if len(sk) != 0 and sk[-1] != '(' and sk[-1] != ')': if op[-1] == '+': v3 = str(int(sk[-1]) + int(num)) else: v3 = str(int(sk[-1]) - int(num)) del op[-1] del sk[-1] sk.append(v3) else: sk.append(num) def calculate(self, s): """ :type s: str :rtype: int """ s = '(' + s s += ')' operator = [] stack = [] numberstring = '0123456789' number = '' for i in s: if i in numberstring: number += i continue else: if len(number) > 0: ##### if stack[-1] != '(' and stack[-1] != ')': self.calc(stack,operator,number) else: stack.append(number) number = '' if i == ' ': continue elif i == '+' or i == '-': operator.append(i) if i == '-' and stack[-1] == '(': stack.append('0') # if input is (-12+1),let it to (0-12+1) elif i == ')': v1 = v2 = v3 = None while stack[-1] != '(': if v1 == None: v1 = stack[-1] v3 = v1 # if input is s.calculate("1") del stack[-1] elif v2 == None: v2 = stack[-1] del stack[-1] if v1 != None and v2 != None: if operator[-1] == '+': v3 = str(int(v2) + int(v1)) else: v3 = str(int(v2) - int(v1)) del operator[-1] v1 = v3 v2 = None del stack[-1] self.calc(stack, operator, v3) elif i == '(': stack.append(i) return int(stack[0])