Concise Java solution using array as stack beats 99.5 percent.


  • 0
    V
        public int evalRPN(String[] tokens) {
            if(tokens == null || tokens.length == 0) return 0;
            String operators = "+-*/";
            long[] stack = new long[tokens.length]; // array used as stack along with len.
            int len = 0; //maintains the stack head.
            for(String chunk : tokens){
                int index = operators.indexOf(chunk); 
                if( index >= 0){
                    if(len < 2) return 0; // invalid string return zero
                    long second = stack[--len], first = stack[--len];
                    if(index == 0)      stack[len++] = first + second;
                    else if(index == 1) stack[len++] = first - second;
                    else if(index == 2) stack[len++] = first * second;
                    else if(index == 3) stack[len++] = first / second; // can have divide by 0 exception
                }else
                    stack[len++] = Long.parseLong(chunk);
            }
            return (int) (len == 1 ? stack[0] : 0);
        }
    

Log in to reply
 

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