题目描述
给定牛牛一个后缀表达式s,计算它的结果,例如,1+1对应的后缀表达式为1#1#+,‘#’作为操作数的结束符号。
其中,表达式中只含有‘+’、’-‘、’*‘三种运算,不包含除法。
本题保证表达式一定合法,且计算过程和计算结果的绝对值一定不会超过10^{18}10 18
使用栈来解决上述问题。遇到+ - * 就出栈。
class Solution:
def solve(self , str ):
stack = []
last = 0
if not str:
return 0
for i in str:
if i >= "0" and i <= "9": # 注意python不可以str-str来判断,cpp可以
if last:
last_num = stack.pop()
stack.append(last_num * 10 + int(i))
last = 1
else:
stack.append(int(i))
last = 1
elif i == "#":
last = 0
continue
else:
if i == "-":
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 - num2)
last = 0
elif i == "+":
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 + num2)
last = 0
else:
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 * num2)
last = 0
if len(stack) > 0:
return stack[0]
else:
return 0