from sys import base_exec_prefix # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 返回表达式的值 # @param s string字符串 待计算的表达式 # @return int整型 # class Solution: def solve(self , s ): s = s.replace(" ","") stack = [] res = 0 num = 0 sign = '+' index = 0 while index < len(s): # 遇到左括号 if s[index] == '(': bracket_end = index + 1 # lens是左括号数量,遇到右括号-1 lens = 1 # bracket_end停在右括号的下一个位置 while lens > 0: if s[bracket_end] == '(': lens += 1 if s[bracket_end] == ')': lens -= 1 bracket_end += 1 #将括号内的内容视为子问题进入递归 num = self.solve(s[index + 1: bracket_end - 1]) # index 跳到右括号的位置 index = bracket_end - 1 continue # 遇到字符数字, 存到变量num if '0' <= s[index] <= '9': num = num * 10 + int(s[index]) # 遇到操作符,将num按规则入栈 # 遇到最后一个数字, 也将num按规则入栈 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) sign = s[index] num = 0 index = index + 1 #栈中元素相加 while stack: res += stack.pop() return res