逆波兰表达式求值(中等)

可以构建一个int类型的栈,在遍历token数组的时候,如果遇到数字,就把字符串类型的数字转化为int类型,放入s栈中,如果遇到加减乘除符号,就把栈顶的两个元素取出来,进行相应的运算操作,然后把计算结果压入栈中。

最后的答案就是栈顶元素,全部处理完后栈中只有一个元素。

java 复制代码
class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack=new Stack<>();
        for(int i=0;i<tokens.length;i++){
            if(tokens[i].equals("+")){
                int x=stack.pop();
                int y=stack.pop();
                int z=x+y;
                stack.push(z);
            }else if(tokens[i].equals("-")){
                int x=stack.pop();
                int y=stack.pop();
                int z=y-x;
                stack.push(z);
            }else if(tokens[i].equals("*")){
                int x=stack.pop();
                int y=stack.pop();
                int z=x*y;
                stack.push(z);
            }else if(tokens[i].equals("/")){
                int x=stack.pop();
                int y=stack.pop();
                int z=y/x;
                stack.push(z);
            }else{
                stack.push(Integer.valueOf(tokens[i]));
            }

        }
        return stack.pop();
    }
}
相关推荐
.YM.Z4 小时前
【数据结构】:排序(一)
数据结构·算法·排序算法
sin_hielo8 小时前
leetcode 2435
数据结构·算法·leetcode
crescent_悦8 小时前
PTA L1-020 帅到没朋友 C++
数据结构·c++·算法
稚辉君.MCA_P8_Java10 小时前
Gemini永久会员 Java动态规划
java·数据结构·leetcode·排序算法·动态规划
cookqq11 小时前
mongodb根据索引IXSCAN 查询记录流程
数据结构·数据库·sql·mongodb·nosql
ohyeah12 小时前
栈:那个“先进后出”的小可爱,其实超好用!
前端·数据结构
历程里程碑13 小时前
各种排序法大全
c语言·数据结构·笔记·算法·排序算法
embrace9914 小时前
【C语言学习】结构体详解
android·c语言·开发语言·数据结构·学习·算法·青少年编程
稚辉君.MCA_P8_Java15 小时前
通义 Go 语言实现的插入排序(Insertion Sort)
数据结构·后端·算法·架构·golang
稚辉君.MCA_P8_Java16 小时前
Gemini永久会员 Go 实现动态规划
数据结构·后端·算法·golang·动态规划