150. Evaluate Reverse Polish Notation

class Solution {
    public int evalRPN(String[] tokens) {
        Deque<Integer> stack = new LinkedList<>();
        // remember String not string
        for(String str : tokens){
            // remember: use of switch
            switch(str){
                case "+":
                    stack.push(stack.pop()+stack.pop());
                    break;
                case "-":
                    stack.push(-1*stack.pop()+stack.pop());
                    break;
                case "*":
                    stack.push(stack.pop()*stack.pop());
                    break;
                case "/":
                    int num=stack.pop();
                    stack.push(stack.pop()/num);
                    break;
                default:
                    // remember: convert string to int: Integer.parseInt(string);
                    stack.push(Integer.parseInt(str));
            }
        }
        
        return (int) stack.pop();
    }
}

Last updated