代码随想录算法训练营第11天 | 复习逆波兰表达式求值

2024年7月13日

逆波兰表达式
记住遇到数字就入栈,遇到符号就取出栈顶的两个数字运算再入栈即可。
注意除法和减法是后出栈的作为被运算数,先出栈的作为运算数。
例如,5在下面,3在上面,那么遇到减法就是5-3而不是3-5。

class Solution {
    public int evalRPN(String[] tokens) {
        int res=-1;
        Stack<Integer> s = new Stack<>();
        for(String x:tokens){
            if(x.equals("+")){
                int x2 = s.pop();
                int x1 = s.pop();
                res = x1+x2;
                s.push(res);
            }else if(x.equals("-")){
                int x2 = s.pop();
                int x1 = s.pop();
                res = x1-x2;
                s.push(res);
            }else if(x.equals("*")){
                int x2 = s.pop();
                int x1 = s.pop();
                s.push(x1*x2);
            }else if(x.equals("/")){
                int x2 = s.pop();
                int x1 = s.pop();
                s.push(x1/x2);
            }else{
                s.push(Integer.valueOf(x));
            }
            
        }
        return s.pop();
    }
}
posted @   hailicy  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示