LeetCode-Evaluate Reverse Polish Notation

本文介绍了一种使用栈解决逆波兰表达式计算问题的方法。通过遍历输入的字符串,识别数字和运算符,并利用栈来存储中间结果,最终计算出逆波兰表达式的值。文章包含详细的Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Note:

  • Division between two integers should truncate toward zero.
  • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won’t be any divide by zero operation.

Example 1:

Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation: 
  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

题意:计算一个逆波兰式的结果

解法:这道题可以利用栈来求解,遍历字符串,如果是数字则压入栈中,否则,在栈中弹出两个数,进行运算(+、-、*、/)后将结果压入栈中;当遍历完所有的字符串后,栈中的那个元素就是最后所要求解的结果;因为,这里保证了所给的逆波兰式是合法的,所以我们不需要去判断合法性;同时,需要注意的一点是,进行计算的时候,栈中弹出的两个数中首先弹出的是第二操作数,后弹出的是第一操作数;

Java
class Solution {
    public int evalRPN(String[] tokens) {
        LinkedList<String> stack = new LinkedList<>();
        for (String s : tokens) {
            if (Character.isDigit(s.charAt(0)) || 
                (s.length() > 1 && Character.isDigit(s.charAt(1)))) {
                stack.push(s);
            } else {
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                int result = 0;
                switch(s.charAt(0)) {
                    case '+':
                        result = num1 + num2;
                        break;
                    case '-':
                        result = num1 - num2;
                        break;
                    case '/':
                        result = num1 / num2;
                        break;
                    case '*':
                        result = num1 * num2;
                        break;
                    default:
                        break;
                }
                stack.push(String.valueOf(result));
            }
        }
        
        return Integer.parseInt(stack.pop());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值