Easy Intuitive Stack JAVA Solution


  • 0
    V
    public class Solution {
        public int evalRPN(String[] tokens) {
            
            Stack<Integer> stack = new Stack<>();
            if (tokens.length == 0) return 0;
            if (tokens.length == 1) return Integer.parseInt(tokens[0]);
            
            for (int i = 0; i < tokens.length; i++) {
                
                // Checking if it is a number. eg: 56 or -5, first char can be a digit or '-' sign, if '-' exist it will be followed by a number
                if (Character.isDigit(tokens[i].charAt(0)) || (tokens[i].length() > 1 && tokens[i].charAt(0) == '-')) stack.push(Integer.parseInt(tokens[i]));
                else {
                    int op2 = stack.pop();
                    int op1 = stack.pop();
                    stack.push(compute(op1, op2, tokens[i].charAt(0)));
                }
            }
            
            return stack.pop();
        }
        
        public int compute(int op1, int op2, char op) {
            if (op == '+') return op1 + op2;
            else if (op == '-') return op1 - op2;
            else if (op == '*') return op1 * op2;
            else if (op == '/') return op1 / op2;
            else return op1 % op2;
        }
    }
    

    Push two digits and when an operator arrives, pop those two digits and apply operation on them!


Log in to reply
 

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