DON'T use Stack when you know the size of it, JAVA, Beats 99%


  • 0
    public class Solution {
        public int evalRPN(String[] tokens) {
            if (tokens == null || tokens.length == 0) {
                return 0;
            }
            int len = tokens.length;
            int[] result = new int[len];
            int pointer = 0;
            for (int i = 0; i < len; i ++) {
                String curr = tokens[i];
                if (Character.isDigit(curr.charAt(curr.length() - 1))) {
                    result[pointer ++] = Integer.parseInt(curr);
                } else {
                    if (curr.equals("+")) {
                        result[pointer - 2] += result[--pointer];
                    } else if (curr.equals("-")) {
                        result[pointer - 2] -= result[--pointer];
                    } else if (curr.equals("*")) {
                        result[pointer - 2] *= result[--pointer];
                    } else {
                        result[pointer - 2] /= result[--pointer];
                    }
                }
            }
            return result[0];
        }
    }

Log in to reply
 

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