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

可以构建一个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();
    }
}
相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1232 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1122 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19432 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww2 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚2 天前
[数据结构] 排序
数据结构
睡不醒的kun2 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌2 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long2 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn2 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap