Simple java stack solution

  • 0
    public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack<Integer>();
            for(int i=0;i<tokens.length;i++){
                if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("/") || tokens[i].equals("*")){
                    int op1 = stack.pop();
                    int op2 = stack.pop();
                    if(tokens[i].equals("+")) stack.push(op2 + op1);
                    else if(tokens[i].equals("-")) stack.push(op2 - op1);
                    else if(tokens[i].equals("*")) stack.push(op2 * op1);
                    else if(tokens[i].equals("/")) stack.push(op2 / op1);
                }else stack.push(Integer.parseInt(tokens[i]));
            return stack.pop();

Log in to reply

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