Z. H.
Z. H.

Reputation: 21

Why does initializing a stack outside of a function perform faster than initializing a stack inside a function?

I'm doing a LeetCode problem and I noticed that my code performs faster when I initialize a Stack before declaring a function as such runs faster:

class Solution {
Stack <Character>myStack = new Stack<Character> ();
public boolean isValid(String s) {
    int sLen=s.length();
    if (sLen%2!=0)
        return false;    
    // Stack <Character>myStack = new Stack<Character> ();
    for(int i=0; i<sLen; i++){
        if ((s.charAt(i)==')')  && !myStack.empty() && (myStack.peek()=='(')) 
            myStack.pop();
        else if (s.charAt(i)==']'  && !myStack.empty() && myStack.peek()=='[')
            myStack.pop();
        else if (s.charAt(i)=='}'  && !myStack.empty() && myStack.peek()=='{')
            myStack.pop();
        else
            myStack.push(s.charAt(i));
    }     
    return myStack.empty();
}}

rather than declaring it inside the boolean function:

class Solution {
//Stack <Character>myStack = new Stack<Character> ();
public boolean isValid(String s) {
    int sLen=s.length();
    if (sLen%2!=0)
        return false;    
    Stack <Character>myStack = new Stack<Character> ();
    for(int i=0; i<sLen; i++){
        if ((s.charAt(i)==')')  && !myStack.empty() && (myStack.peek()=='(')) 
            myStack.pop();
        else if (s.charAt(i)==']'  && !myStack.empty() && myStack.peek()=='[')
            myStack.pop();
        else if (s.charAt(i)=='}'  && !myStack.empty() && myStack.peek()=='{')
            myStack.pop();
        else
            myStack.push(s.charAt(i));
    }     
    return myStack.empty();
}}

Upvotes: 0

Views: 38

Answers (1)

Christian
Christian

Reputation: 22343

That's because in the first snippet, you initialize your myStack ony once, while in your second snippet, you initialize it inside a method and so the myStack gets initialized each time the isValid method gets called.

Upvotes: 1

Related Questions