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

可以构建一个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();
    }
}
相关推荐
whitepure1 小时前
万字详解常用数据结构(Java版)
java·数据结构·后端
2025年一定要上岸2 小时前
【数据结构】-4-顺序表(上)
java·开发语言·数据结构
Vect__17 小时前
链表漫游指南:C++ 指针操作的艺术与实践
数据结构·c++·链表
古译汉书17 小时前
蓝桥杯算法之基础知识(2)——Python赛道
数据结构·python·算法·蓝桥杯
.Vcoistnt17 小时前
Codeforces Round 1043 (Div. 3)(A-E)
数据结构·算法
野犬寒鸦17 小时前
力扣hot100:搜索二维矩阵与在排序数组中查找元素的第一个和最后一个位置(74,34)
java·数据结构·算法·leetcode·list
啊吧怪不啊吧1 天前
C++之list类的代码及其逻辑详解 (中)
开发语言·数据结构·c++·list
楼田莉子1 天前
C++算法学习专题:滑动窗口
开发语言·数据结构·c++·学习·算法·leetcode
zh_xuan1 天前
LeeCode 40.组合总和II
c语言·数据结构·算法
wangluoqi1 天前
c++ 数据结构-并查集、ST表 小总结
数据结构·c++