#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 返回表达式的值
# @param s string字符串 待计算的表达式
# @return int整型
#
class Solution:
def solve(self, s: str) -> int:
# write code here
st = [] # 辅助栈
num = ""
for i in s:
if i in "(+-*":
if num != "":
st.append(int(num)) # 数字入栈
num = ""
st.append(i) # 符号入栈
elif i == ")":
if num != "":
st.append(int(num)) # 数字入栈
num = ""
t = st.pop()
sth = [] # 辅助栈
while t != "(": # 将"("前的所有移到辅助栈,将乘法优先计算
if t != "*":
sth.append(t)
else:
a = sth.pop()
b = st.pop()
sth.append(a * b)
t = st.pop()
# 所有的括号中乘法计算完了再计算加减
while len(sth) != 1:
a = int(sth.pop())
c = sth.pop()
b = int(sth.pop())
if c == "+":
sth.append(a + b)
if c == "-":
sth.append(a - b)
st.append(sth[0]) # 将结果入栈
else:
num = num + i # 拼接数字
if num != "":
st.append(int(num)) # 不带括号的字符串最后一个数字的处理
st = st[::-1] # 从最后出栈,数组逆序,便于加减顺序计算
while len(st) != 1: # 解决完所有括号的加减乘计算
a = int(st.pop())
c = st.pop()
b = int(st.pop())
if c == "+":
st.append(a + b)
if c == "-":
st.append(a - b)
if c == "*":
st.append(a * b)
return st[0]
做了前五道题做这个还是错误频出啊...
不过还好最后做出来了!好耶
很多要注意的点:
(10+20*10-6)这样的括号内乘法,要考虑乘法优先计算
1-2-3这样的减法运算只能顺序计算
数字不是个位,要进行拼接

京公网安备 11010502036488号