Evaluate Reverse Polish Notation ---Java

一道LeetCode上的老题目,之所以再写出来,是因为看到一位老司机的解题方法.
首先这道题是, 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

思路:遍历数组,碰到操作数入栈,碰到操作符就从栈顶取出两个操作数,再将计算后的结果入栈.

在牛客网上看到一位老司机的解法是这样的:

import java.util.Stack;
public class Solution {
    public int evalRPN(String[] tokens) {
        Stack stack = new Stack();
        for(int i = 0;itry{
                int num = Integer.parseInt(tokens[i]);
                stack.add(num);
            }catch (Exception e) {
                int b = stack.pop();
                int a = stack.pop();
                stack.add(get(a, b, tokens[i]));
            }
        }
        return stack.pop();
    }
    private int get(int a,int b,String operator){
        switch (operator) {
        case "+":
            return a+b;
        case "-":
            return a-b;
        case "*":
            return a*b;
        case "/":
            return a/b;
        default:
            return 0;
        }
    }
}

附上传送门牛客网-老石基
作者老石基,,这个异常用的,教科书版本.<我少见多怪了,哈哈>

另附上我的方式:

import java.util.Stack;
public class Call {
    public static int evalRPN(String[] tokens) {
        Stack strings = new Stack<>();

        for (int i = 0; i < tokens.length; i++) {

            switch (tokens[i]) {
                case "+":
                    strings.push(String.valueOf(stringToInt(strings.pop()) + stringToInt(strings.pop())));
                    break;

                case "-":
                    String a = strings.pop();
                    String b = strings.pop();
                    strings.push(String.valueOf(stringToInt(b) - stringToInt(a)));
                    break;

                case "*":
                    strings.push(String.valueOf(stringToInt(strings.pop()) * stringToInt(strings.pop())));
                    break;

                case "/":
                    String c = strings.pop();
                    String d = strings.pop();
                    strings.push(String.valueOf(stringToInt(d) / stringToInt(c)));
                    break;

                default:
                    strings.push(tokens[i]);
                    break;
            }
        }

        return Integer.valueOf(strings.pop());
    }

    static int stringToInt(String s) {
        return Integer.valueOf(s);
    }
}

还是这个思路,,但实现方式就显得很是平常,甚至有点儿菜.

你可能感兴趣的:(算法)