Fast and Simple Java, no stack object or recursion


  • 1
    N

    It (technically) doesn't use a Java Stack and it shocked me by beating 95% when I first submit it... o.O The extra speed is from the use of primitives rather than classes.

    It also relies on the string being only braces. If test cases are added with extra chars than that final else if would need to exclude non brace characters from the check.

    public boolean isValid(String s) {
            char[] array = s.toCharArray();
    
            int pointer = 0;
            char[] stack = new char[array.length];
            
            for (char c : array){
                if (c == '(') stack[pointer++] = ')';
                else if (c == '{') stack[pointer++] = '}';
                else if (c == '[') stack[pointer++] = ']';
                else if (pointer == 0 || stack[--pointer] != c)
                {
                    return false;
                }
            }
            return pointer == 0;
        }
    

  • 0
    Y
    This post is deleted!

  • 0
    G

    very nice solution ^_^


Log in to reply
 

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