Why got Time Limit Exceeded using stack implementation


  • 1
    S
    import java.util.Stack;
    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));
                }
            }
            
            return myStack.pop();
        }
    }

Log in to reply
 

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