【LeetCode刷题-栈】-- 150.逆波兰表达式求值

150.逆波兰表达式求值

方法:使用栈

java 复制代码
class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> numStack = new Stack<>();
        for(int i = 0; i < tokens.length;i++){
            String token = tokens[i];
            if(isNumber(token)){
                numStack.push(Integer.parseInt(token));
            }else{
                int num1 = numStack.pop();
                int num2 = numStack.pop();
                switch(token){
                    case "+":
                        numStack.push(num1 + num2);
                        break;
                    case "-":
                        numStack.push(num2 - num1);
                        break;
                    case "*":
                        numStack.push(num1 * num2);
                        break;
                    case "/":
                        numStack.push(num2 / num1);
                        break;
                    default:
                }
           
            }
        }
        return numStack.pop();
    }
    public boolean isNumber(String token){
        return !("+".equals(token) || "-".equals(token) || "*".equals(token) || "/".equals(token));
    }
}
相关推荐
sali-tec8 小时前
C# 基于halcon的视觉工作流-章66 四目匹配
开发语言·人工智能·数码相机·算法·计算机视觉·c#
小明说Java8 小时前
常见排序算法的实现
数据结构·算法·排序算法
行云流水20199 小时前
编程竞赛算法选择:理解时间复杂度提升解题效率
算法
smj2302_7968265210 小时前
解决leetcode第3768题.固定长度子数组中的最小逆序对数目
python·算法·leetcode
cynicme11 小时前
力扣3531——统计被覆盖的建筑
算法·leetcode
core51211 小时前
深度解析DeepSeek-R1中GRPO强化学习算法
人工智能·算法·机器学习·deepseek·grpo
mit6.82412 小时前
计数if|
算法
a伊雪12 小时前
c++ 引用参数
c++·算法
圣保罗的大教堂12 小时前
leetcode 3531. 统计被覆盖的建筑 中等
leetcode