150. Evaluate Reverse Polish Notation

算术表达式的计算

原题链接请点击

题意:

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

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

Some examples:
[“2”, “1”, “+”, “3”, ““] -> ((2 + 1) 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6

法一:非递归

  1. 建立一个栈存储数字
  2. 遇到符号,数字栈的前两个弹出,注意顺序!后弹出的+-*/先弹出的
  3. 计算结果压回栈中
  4. 计算结束后,s.peek()即为所求结果。
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (String s : tokens) {
            switch (s) {
            case "+":
                stack.push(stack.pop() + stack.pop());
                break;
            case "-":
                int temp = stack.pop();
                stack.push(stack.pop() - temp);
                break;
            case "*":
                stack.push(stack.pop() * stack.pop());
                break;
            case "/":
                temp = stack.pop();
                stack.push(stack.pop() / temp);
                break;

            default:
                stack.push(Integer.parseInt(s));
                break;
            }
        }
        return stack.peek();
    }

法二:递归

  • 从后往前检查数组,遍历到符号时,不断循环找到两个数;遍历到数时,parseInt转成Integer。如果遇到新符号,先计算新符号。
public class Solution {
    int index;
    public int evalRPN(String[] tokens) {
        index = tokens.length - 1;
        return recurse(tokens);
    }
    private int recurse(String[] tokens) {
        String word = tokens[index--];
        int a, b;
        switch (word) {
        case "+":
            b = recurse(tokens);
            a = recurse(tokens);
            return a + b;
        case "-":
            b = recurse(tokens);
            a = recurse(tokens);
            return a - b;
        case "*":
            b = recurse(tokens);
            a = recurse(tokens);
            return a * b;
        case "/":
            b = recurse(tokens);
            a = recurse(tokens);
            return a / b;
        default:
            return Integer.parseInt(word);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值