LeetCode 150 : Evaluate Reverse Polish Notation

277 阅读1分钟
/**
 * 150. Evaluate Reverse Polish Notation
 * 1. Time:O(n)  Space:O(n)
 * 2. Time:O(n)  Space:O(n)
 */

// 1. Time:O(n)  Space:O(n)
class Solution {
    private static String OPS = "+-*/";
    public int evalRPN(String[] tokens) {
        if(tokens==null || tokens.length==0) return 0;
        Stack<String> stack = new Stack<>();
        for(String s:tokens){
            if(!isOperator(s))
                stack.push(s);
            else{
                int y = Integer.parseInt(stack.pop());
                int x = Integer.parseInt(stack.pop());
                switch(s.charAt(0)){
                    case '+': 
                        x += y;
                        break;
                    case '-':
                        x -= y;
                        break;
                    case '*':
                        x *= y;
                        break;
                    default:
                        x /= y;
                }
                stack.push(String.valueOf(x));
            }
        }
        return Integer.parseInt(stack.peek());
    }
    
    private static boolean isOperator(String op){
        return op.length()==1 && OPS.indexOf(op)!=-1;
    }
}

// 2. Time:O(n)  Space:O(n)
class Solution {
    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 "-":
                    stack.push(-stack.pop()+stack.pop());
                    break;
                case "*":
                    stack.push(stack.pop()*stack.pop());
                    break;
                case "/":
                    int y = stack.pop(), x = stack.pop();
                    stack.push(x/y);
                    break;
                default:
                    stack.push(Integer.parseInt(s));
            }
        }
        return stack.pop();
    }
}