150-计算逆波兰表达式

本文介绍了一种计算逆波兰表达式的值的方法,通过使用栈结构实现两种解法:迭代和递归。迭代方法利用栈进行操作数和运算符的处理,而递归方法则通过递归地评估表达式的各个部分。

Description

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

问题描述

计算逆波兰表达式的值。
有效的操作符为 + , -, *, 或者 / .每个操作数为整数或者一个表达式的值


问题分析

如果对逆波兰表达式求值和如何产生后缀表达式如熟悉的话,可以看看这两篇文章

如何产生后缀表达式
https://en.wikipedia.org/wiki/Shunting-yard_algorithm
逆波兰表达式求值
https://en.wikipedia.org/wiki/Reverse_Polish_notation

解法2有点特殊,递归处理逆序遍历


解法1(迭代)

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<Integer>();

        for(String str : tokens){
            if(str.equals("+")){
                int num = stack.pop();
                stack.push(stack.pop() + num);
            }else if(str.equals("-")){
                int num = stack.pop();
                stack.push(stack.pop() - num);
            }else if(str.equals("*")){
                int num = stack.pop();
                stack.push(stack.pop() * num);
            }else if(str.equals("/")){
                int num = stack.pop();
                stack.push(stack.pop() / num);
            }else{
                stack.push(Integer.valueOf(str));
            }
        }

        return stack.pop();
    }
}

解法2(递归)

class Solution {
    private int curr;
    public int evalRPN(String[] tokens) {
        curr = tokens.length - 1;
        return eval(tokens);
    }

    private int eval(String[] tokens) {
        String token = tokens[curr--];
        char c = token.charAt(0);
        if (token.length() == 1 && isOp(c)) {
            int b = eval(tokens);
            int a = eval(tokens);
            return applyOp(c, a, b);
        } else {
            return Integer.parseInt(token);
        }
    }

    private boolean isOp(char c) {
        switch (c) {
            case '+': case '-': case '*': case '/': return true;
        }
        return false;
    }

    private int applyOp(char op, int a, int b) {
        switch (op) {
            case '+': return a + b;
            case '-': return a - b;
            case '*': return a * b;
            case '/': return a / b;
        }
        return a;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值