美文网首页
LeetCode 第 150 题:逆波兰表达式求值

LeetCode 第 150 题:逆波兰表达式求值

作者: 放开那个BUG | 来源:发表于2023-03-03 19:51 被阅读0次

1、前言

题目描述

2、思路

遇到数字就入栈,遇到符号就出栈,然后将结果入栈

3、代码

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<String> stack = new Stack<>();
        for(String token : tokens){
            if(token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")){
                int num1 = Integer.parseInt(stack.pop()), num2 = Integer.parseInt(stack.pop());
                if(token.equals("+")){
                    stack.push((num2 + num1) + "");
                }
                if(token.equals("-")){
                    stack.push((num2 - num1) + "");
                }
                if(token.equals("*")){
                    stack.push((num2 * num1) + "");
                }
                if(token.equals("/")){
                    stack.push((num2 / num1) + "");
                }
            }else{
                stack.push(token);
            }
        }

        return Integer.parseInt(stack.pop());
    }
}

相关文章

网友评论

      本文标题:LeetCode 第 150 题:逆波兰表达式求值

      本文链接:https://www.haomeiwen.com/subject/giskurtx.html