#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 返回表达式的值
# @param s string字符串 待计算的表达式
# @return int整型
#
import re
class Solution:
def solve(self , s: str) -> int:
# write code here
stack = []
ls = self.infix_to_postfix(s)
for it in ls:
if it.isdigit():
stack.append(int(it))
elif it=="+":
stack.append(stack.pop()+stack.pop())
elif it=="*":
stack.append(stack.pop()*stack.pop())
elif it=="-":
stack.append(-(stack.pop()-stack.pop()))
else:
pass
return stack[0]
def infix_to_postfix(self, s: str) -> list:
prec = {'+': 1, '-': 1, '*': 2}
res = []
stack = []
tokens = re.findall(r'\d+|[()+*\-]', s)
for token in tokens:
if token.isdigit():
res.append(token)
elif token == '(':
stack.append(token)
elif token == ')':
while stack and stack[-1] != '(':
res.append(stack.pop())
stack.pop()
else:
while stack and stack[-1] != '(' and prec[stack[-1]] >= prec[token]:
res.append(stack.pop())
stack.append(token)
while stack:
res.append(stack.pop())
print(res)
return res