代码随想录算法训练营第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 @ 2024-07-14 15:09  hailicy  阅读(2)  评论(0编辑  收藏  举报