150. Evaluate Reverse Polish Notation

T: O(n)
S: O(n)
class Solution {
    public int evalRPN(String[] tokens) {
        ArrayDeque<Integer> stack = new ArrayDeque<>();
        for (String s : tokens) {
            if ("+".equals(s) || "-".equals(s) || "*".equals(s) || "/".equals(s)) {
                int b = stack.pop();
                int a = stack.pop();

                if ("+".equals(s)) {
                    stack.push(a+b);
                    
                } else if ("-".equals(s)) {
                    stack.push(a-b);
                    
                } else if ("*".equals(s)) {
                    stack.push(a*b);
                    
                } else if ("/".equals(s)) {
                    stack.push(a/b);
                }
            } else {
                stack.push(Integer.valueOf(s));
            }
        }
        return stack.peek();
    }
}

/*

้—œ้ต, ๅšๅฎŒ็ตๆžœ่ฆๆ”พๅ›ž stack

T: O(n)
S: O(n)

*/

Last updated