1ms java solution with stack


  • 0
    H
    public boolean isValid(String s) {
            if(s == null || s.length() == 1){
                return false;
            }
            
            Stack<Character> theStack = new Stack<Character>();
            char[] brackets = s.toCharArray();
            for(char c: brackets){
                if(c == '(' || c == '{' || c=='['){
                    theStack.push(c);
                }else{
                    if(theStack.isEmpty()){
                        return false;
                    }
                    char bracket = theStack.pop();
                    if(c==')' && bracket!='(' || c=='}' && bracket!='{' || c==']' && bracket!='['){
                        return false;
                    }
                }
                
            }
            if(theStack.isEmpty()){
                return true;    
            }
            return false;
            
        }

Log in to reply
 

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