题解 | 表达式求值
表达式求值
https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 返回表达式的值 # @param s string字符串 待计算的表达式 # @return int整型 # class Solution: def solve(self , s: str) -> int: # write code here l=[] stack=[] stack2=[] num="" d={"(":0,"*":2,"+":1,"-":1} for t in s: if t == ' ': continue elif t.isdigit(): num+=t else: if num: l.append(num) num = "" if t == '(': stack.append(t) elif t==")": while stack and (stack[-1]!="("): l.append(stack.pop()) stack.pop() else: while stack and d[stack[-1]]>=d[t]: l.append(stack.pop()) stack.append(t) if num: l.append(num) while stack: l.append(stack.pop()) print(l) for i in l: if i.isdigit(): stack2.append(int(i)) else: if stack2: b=stack2.pop() a=stack2.pop() if i=="+": stack2.append(a+b) elif i=="-": stack2.append(a-b) elif i=="*": stack2.append(a*b) print(stack2) return stack2[0] if stack2 else 0