JAVA--6ms---beats 99.64% !


  • 7
    S

    6MS---JAVA

    public int evalRPN(String[] tokens) {
     int[] ls = new int[tokens.length/2+1];
        int index = 0;
        for (String token : tokens) {
            switch (token) {
                case "+":
                    ls[index - 2] = ls[index - 2] + ls[index - 1];
                    index--;
                    break;
                case "-":
                    ls[index - 2] = ls[index - 2] - ls[index - 1];
                    index--;
                    break;
                case "*":
                    ls[index - 2] = ls[index - 2] * ls[index - 1];
                    index--;
                    break;
                case "/":
                    ls[index - 2] = ls[index - 2] / ls[index - 1];
                    index--;
                    break;
                default:
                    ls[index++] = Integer.parseInt(token);
                    break;
            }
        }
        return ls[0];
    }

  • 1
    S

    What a brilliant solution!! Getting rid of stack!!
    One minor change suggested can make it shorter:

    ls[index - 2] = ls[index - 2] / ls[--index];
    

  • 0
    D

    @SunnyYuen It's still using an array as a "stack" s.t. index is the stack top.


  • 0
    S

    @dingty yes, it's actually a simplified stack but that shows his understanding of the essence in this problem.


  • 0
    D

    @SunnyYuen Sure, just want to confirm you really understand it since you've said "Getting rid of stack!!".


Log in to reply
 

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