Beat 97% Java concise solution


  • 0
    public class Solution {
        public int evalRPN(String[] tokens) {
            Deque<Integer> stack = new ArrayDeque();
            for (String s : tokens) {
                if (s.charAt(s.length() - 1) >= '0' && s.charAt(s.length() - 1) <= '9') { // if it's number
                    stack.push(Integer.valueOf(s));
                } else { // +-*/
                    int cur = stack.pop(), pre = stack.pop();
                    stack.push(cal(pre, s.charAt(0), cur));
                }
            }
            return stack.pop();
        }
        
        private int cal(int a, char p, int b) {
            switch (p) {
                case '+': return a + b;
                case '-': return a - b;
                case '*': return a * b;
                case '/': return a / b;
            }
            return -1;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.