一眼看过去很简单,实际写的时候发现很多坑。
1.第一步:先不管括号的问题
2.第二步:先不管乘法问题
3.第三步:实现加减运算
4.第四步:解决连续数字问题
class Solution: def solve(self, s: str) -> int: num, opt, stack = 0, '+', [] while s: item,s = s[0],s[1:] if(item=='('): lens,end = 1,0 while lens > 0: if s[end] == '(': lens += 1 if s[end] == ')': lens -= 1 end += 1 num = self.solve(s[0:end - 1]) s = s[end:] elif item.isdigit(): num = num*10+int(item) if not item.isdigit() or not s: if opt == '+': stack.append(num) elif opt == '-': stack.append(-num) elif opt =='*': stack.append(stack.pop()*num) num,opt =0, item return sum(stack)