Easy and clean Java using Stack!


  • 0
    S
    public class Solution {
        private static final String PLUS = "+", MINUS = "-", MULT = "*", DIV = "/";
        public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack();
            for (int i = 0; i < tokens.length; i++) {
                try {
                    int x = Integer.parseInt(tokens[i]);
                    stack.push(x);
                } catch (Exception e) {
                    /* Not an integer*/
                    String operator = tokens[i];
                    int first = stack.pop(), second = stack.pop();
                    if (operator.equals(PLUS)) {
                        stack.push(second + first);
                    } else if (operator.equals(MINUS)) {
                        stack.push(second - first);
                    } else if (operator.equals(MULT)) {
                        stack.push(second * first);
                    } else {
                        stack.push(second / first);
                    }
                }
            }
            return stack.pop();
        }
    }
    

Log in to reply
 

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