My Accepted Solution: recursion is a good way!


  • 0
    F
    public class Solution {
        private String[] tokens;
        private int p;
    
        public int evalRPN(String[] tokens) {
            this.tokens = tokens;
            p = tokens.length - 1;
            return getValue();
        }
    
        private int getValue() {
            String s = tokens[p--];
            if ("+-*/".indexOf(s) == -1) {
                return Integer.parseInt(s);
            }
            int v2 = getValue();
            int v1 = getValue();
            char op = s.charAt(0);
            switch (op) {
                case '+':
                    return v1 + v2;
                case '-':
                    return v1 - v2;
                case '*':
                    return v1 * v2;
                case '/':
                    return v1 / v2;
            }
            throw new RuntimeException("impossible");
        }
    }

Log in to reply
 

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