题解 | 表达式求值

表达式求值

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

                    
            
        
            



全部评论

相关推荐

04-13 18:10
门头沟学院 Java
想熬夜的小飞象在秋招:被腾讯挂了后爸妈以为我失联了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务