def calculate(s: str) -> int: def precedence(op): """定义运算符优先级:乘除 > 加减""" return 2 if op in ('*', '/') else 1 def apply_op(a: int, b: int, op: str) -> int: """执行运算""" if op == '+': return a + b elif op == '-': return a - b elif op == '*': return a * b elif op == '/': return a // b 整数除法,可根据需求改为浮点数除法 预处理:去除空格,大括号转为小括号(仅支持小括号逻辑) s = s.replace(' ', '').replace('{', '(').replace('}', ')') nums = [] 数字栈 ops = [] 运算符栈 i = 0 n = len(s) while i < n: if s[i].isdigit(): 处理多位数(如123) num = 0 while i < n and s[i].isdigit(): num = num * 10 + int(s[i]) i += 1 nums.append(num) elif s[i] == '(': ops.append(s[i]) i += 1 elif s[i] == ')': 遇到右括号,弹出运算符直到左括号 while ops and ops[-1] != '(': b = nums.pop() a = nums.pop() op = ops.pop() nums.append(apply_op(a, b, op)) ops.pop() 弹出左括号 i += 1 elif s[i] in ('+', '-', '*', '/'): 处理运算符优先级:当前运算符优先级≤栈顶时,先执行栈顶运算 while ops and ops[-1] != '(' and precedence(ops[-1]) >= precedence(s[i]): b = nums.pop() a = nums.pop() op = ops.pop() nums.append(apply_op(a, b, op)) ops.append(s[i]) i += 1 else: raise ValueError("无效字符:" + s[i]) 处理剩余运算符 while ops: b = nums.pop() a = nums.pop() op = ops.pop() nums.append(apply_op(a, b, op)) return nums[0]