Easy to understand Java Solution With Stack O(n) -- With Comments for understanding


  • 1
    public class Solution {
        
        public boolean isValid(String s) {
            
            //Base Check
            if (s == null || s.equals("") || s.trim().equals("")) {
                return true;
            }
            
            //Create new stack, to push only open braces
            Stack<Character> bracketStack = new Stack<>();
            char[] inputArray = s.toCharArray();
            
            //Loop through the input.
            for (char item : inputArray) {
                //Switch case is preferred here to improve runtime, since a switch case is generally faster than a long list
                //of if-elses
                switch(item) {
                
                case '}':
                    if (bracketStack.isEmpty()) {
                        return false;
                    } else {
                        char pop = bracketStack.pop();
                        if (pop != '{') {
                            return false;
                        }
                    }
                    break;
                    
               case ']':
                   if (bracketStack.isEmpty()) {
                        return false;
                    } else {
                        char pop = bracketStack.pop();
                        if (pop != '[') {
                            return false;
                        }
                    }
                    break;
                    
               case ')':
                   if (bracketStack.isEmpty()) {
                        return false;
                    } else {
                        char pop = bracketStack.pop();
                        if (pop != '(') {
                            return false;
                        }
                    }
                    break;
                    
                default:
                    bracketStack.push(item);
                }
            }
            
            //returns true if stack is empty and false when there are residual values.
            return bracketStack.isEmpty();
        }
    } 
    

Log in to reply
 

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