LeetCode 150 逆波兰表达式求值

简介: 构造一个栈,遇到运算符就弹出进行运算

题目

image.png


思路

构造一个栈,遇到运算符就弹出进行运算

class Solution {
    public int evalRPN(String[] tokens) {
        Deque<Integer> stack = new ArrayDeque<>();
        for(String s : tokens){
            int num1,num2;
            //正则表达式匹配数字
            if(s.matches("\\d+")){
                int num = Integer.parseInt(s);
                stack.push(num);
            }else if(s.length()>1 && s.charAt(0)=='-'){//匹配负数
                    int num = Integer.parseInt(s);
                    stack.push(num);
                }else{
                switch(s){
                    case "+":
                        num1 = stack.pop();
                        num2 = stack.pop();
                        stack.push(num1+num2);
                        break;
                    case "-":
                        num1 = stack.pop();
                        num2 = stack.pop();
                        stack.push(num2-num1);
                        break;
                    case "*":
                        num1 = stack.pop();
                        num2 = stack.pop();
                        stack.push(num1*num2);
                        break;
                    case "/":
                        num1 = stack.pop();
                        num2 = stack.pop();
                        stack.push(num2/num1);
                        break;
                }
            }
        }
        return stack.pop();
    }
}


相关文章
|
4月前
|
算法 Go
golang力扣leetcode 399.除法求值
golang力扣leetcode 399.除法求值
42 0
|
2月前
|
算法 测试技术
力扣经典150题第五十五题:逆波兰表达式求值
力扣经典150题第五十五题:逆波兰表达式求值
21 1
|
4月前
|
索引
【力扣刷题】数组实现栈、后缀表达式(逆波兰表达式)求值、中缀表达式转换为后缀表达式(无括号&&有括号)
【力扣刷题】数组实现栈、后缀表达式(逆波兰表达式)求值、中缀表达式转换为后缀表达式(无括号&&有括号)
34 0
|
4月前
leetcode代码记录(逆波兰表达式求值
leetcode代码记录(逆波兰表达式求值
26 0
|
4月前
|
存储 人工智能 BI
leetcode 399 除法求值
leetcode 399 除法求值
25 1
|
4月前
|
Java
LeetCode题解-逆波兰表达式求值-Java
逆波兰表达式求值-Java
25 0
|
4月前
|
Go
golang力扣leetcode 150.逆波兰表达式求值
golang力扣leetcode 150.逆波兰表达式求值
34 0
|
4月前
|
存储 算法 vr&ar
☆打卡算法☆LeetCode 150. 逆波兰表达式求值 算法解析
☆打卡算法☆LeetCode 150. 逆波兰表达式求值 算法解析
|
24天前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
36 6
|
24天前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
54 2