LeetCode224:基本计算器(栈)
解题思路:
1、双栈模拟,一个用来存数,一个用来存操作符。需要考虑 '('后面紧跟'+'、'-'这种情况
2、递归:遇到左括号开始递归,遇到右括号结束递归,返回值。
1 class Solution: 2 def calculate(self, s): 3 s = '('+s+')' 4 stack = [] 5 op = [] 6 val = 0 7 flag = False 8 for i in range(len(s)): 9 if ord('0')<=ord(s[i])<=ord('9'): 10 val=val*10+ord(s[i])-ord('0') 11 flag= True 12 elif s[i]=='(': 13 op.append('(') 14 stack.append('(') 15 elif s[i]==')': 16 if flag: 17 stack.append(val) 18 flag = False 19 val = 0 20 ans = 0 21 while op[-1]!='(' and stack[-1]!='(': 22 if op[-1]=='+': 23 ans = ans + stack[-1] 24 elif op[-1]=='-': 25 ans = ans - stack[-1] 26 _,_= stack.pop(),op.pop() 27 28 if op[-1]=='(' and stack[-1]=='(': 29 _ = op.pop(),stack.pop() 30 elif op[-1]=='(': 31 ans+=stack[-1] 32 _ = stack.pop() 33 _ = op.pop(), stack.pop() 34 else: 35 print('error') 36 exit() 37 stack.append(ans) 38 elif s[i]=='+': 39 if flag: 40 stack.append(val) 41 flag=False 42 val = 0 43 op.append('+') 44 elif s[i]=='-': 45 if flag: 46 stack.append(val) 47 flag =False 48 val=0 49 op.append('-') 50 elif s[i]==' ': 51 continue 52 return stack[-1] 53 s = Solution().calculate("0+0+(-0+0)") 54 print(s)