Why this stack implementation exceed time limit?


  • 1
    S
    public class Solution {
        public int evalRPN(String[] tokens) {
            Stack<Integer> myStack = new Stack<Integer>();
            int val1, val2;
            for (String item : tokens) {
                if (item.equals("+")) {
                    myStack.push(myStack.pop() + myStack.pop());
                }
                else if (item.equals("-")) {
                    val1 = myStack.pop();
                    val2 = myStack.pop();
                    myStack.push(val2 - val1);
                }
                else if (item.equals("*")) {
                    myStack.push(myStack.pop() * myStack.pop());
                }
                else if (item.equals("/")) {
                    val1 = myStack.pop();
                    val2 = myStack.pop();
                    myStack.push(val2 / val1);
                }
                else {
                    myStack.push(Integer.parseInt(item));
                }
            }
            //System.out.println(myStack.peek());
            
            return myStack.pop();
            
        }
    }

  • 0

    Please try again, it should get accepted now.


Log in to reply
 

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