【名词解释】
"1#1#+"
2
1#1#+这个后缀表达式表示的式子是1+1,结果为2
"12#3#+15#*"
225
12#3#+15#*这个后缀表达式表示的式子是(12+3)*15,结果为225
"1#1#4#5#-*+1#4#*+"
4
class Solution:
def legalExp(self , str ):
# write code here
num_stack = []
stack = []
for x in str:
if x.isdigit() == True :
num_stack.append(x)
elif x == "#":
num = int ("".join(num_stack))
stack.append(num)
num_stack.clear()
elif x in "+-*":
num1 = stack.pop()
num2 = stack.pop()
if x == "+":
stack.append(num2+num1)
elif x == "-":
stack.append(num2-num1)
elif x == "*":
stack.append(num2*num1)
return stack[-1] def calculate(number1, number2, Symbol): if Symbol == "*": return number1 * number2 elif Symbol == "+": return number1 + number2 elif Symbol == "-": return number2 - number1 class Solution: def legalExp(self , str ): stack = [] symbol = "+-*" number = 0 for i in str: if i.isdigit(): number = number * 10 + int(i) elif i == "#": stack.append(number) number = 0 elif i in symbol: temp1 = int(stack.pop()) temp2 = int(stack.pop()) stack.append(calculate(temp1, temp2, i)) return stack.pop()
import re # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 给定一个后缀表达式,返回它的结果 # @param str string字符串 # @return long长整型 # class Solution: def legalExp(self , str ): # write code here s = re.findall(r'\d+|[+*#\-]', str) new_s = [] list_s = [] for j in s: if j == "#": continue else: new_s.append(j) res = 0 for i in new_s: if i == "+": res = int(list_s[-2]) + int(list_s[-1]) list_s[-2] = int(res) list_s.pop() elif i == "-": res = int(list_s[-2]) - int(list_s[-1]) list_s[-2] = int(res) list_s.pop() elif i == "*": res = int(list_s[-2]) * int(list_s[-1]) list_s[-2] = int(res) list_s.pop() else: list_s.append(i) return res
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 给定一个后缀表达式,返回它的结果
# @param str string字符串
# @return long长整型
#
class Solution:
def legalExp(self , str ):
# write code here
def apply_op(a,b,op):
if op == "+":return a+b
if op == "-":return a-b
if op == "*":return a*b
stack = []
i = 0
while i < len(str):
if str[i].isdigit():
num = 0
while i < len(str) and str[i].isdigit():
num = num *10 + int(str[i])
i += 1
stack.append(num)
elif str[i] == "#":
i += 1
elif str[i] in ("+","-","*"):
num1 = stack.pop()
num2 = stack.pop()
op = str[i]
stack.append(apply_op(num2,num1,op))
i += 1
return int(stack[0])
if __name__ == "__main__":
s = str(input().strip().replace('"',''))
print(Solution().legalExp(s))