三刷Evaluate Reverse Polish Notation

Linkedin Medium
这道题用Stack of Integer要方便得多,用Stack of string则要来回转换。

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (String token : tokens){
            if (token.equals("+")){
                int num1 = stack.pop();
                int num2 = stack.pop();
                int sum = num1 + num2;
                stack.push(sum);
            } else if (token.equals("-")){
                int num1 = stack.pop();
                int num2 = stack.pop();
                int subs = num2 - num1;
                stack.push(subs);
            } else if (token.equals("*")){
                int num1 = stack.pop();
                int num2 = stack.pop();
                int prod = num1 * num2;
                stack.push(prod);
            } else if (token.equals("/")){
                int num1 = stack.pop();
                int num2 = stack.pop();
                int quot = num2 / num1;
                stack.push(quot);
            } else {
                int num = Integer.parseInt(token);
                stack.push(num);
            }
        }
        return stack.pop();
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/6f77ba601337
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞