遇到这种使用栈来做计算,就有些迷糊,这是看了答案来理解的。
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 返回表达式的值
# @param s string字符串 待计算的表达式
# @return int整型
#
class Solution:
def solve(self , s: str) -> int:
# write code here
#使用递归和栈
s = s.strip()#去除空格
stack = []
num = 0
index = 0
sign = '+'
res = 0
while index < len(s):
if s[index]==' ':
index += 1
continue
#遇到左括号,进入递归
if s[index] == '(':
end = index + 1
lens = 1
while lens > 0:
if s[end] == '(':
lens += 1
if s[end] == ')':
lens -= 1
end += 1
#将本层级括号的内容视为子问题进入递归
num = self.solve(s[index+1 : end-1])
index = end - 1#?
continue
#字符数字转换成int格式,核心步骤
if '0' <= s[index] <='9':
num = num*10 + int(s[index])#多位数的情况
#根据符号进行计算
if not '0'<=s[index]<='9' or index==len(s)-1:
if sign == '+':
stack.append(num)
elif sign == '-':
stack.append(-1*num)
elif sign == '*':
stack.append(stack.pop()*num)
num = 0
sign = s[index]
index += 1
while stack:
res += stack.pop()
return res