Balanced Brackets

  • + 0 comments

    Java Solution:

        public static String isBalanced(String s) {
            char[] arr = s.toCharArray();
            Stack<Character> stack = new Stack<>();
            for(char c : arr){
                if(c == '{' || c == '(' || c == '['){
                    stack.push(c);
                }
                
                if(c == '}' || c == ')' || c == ']'){
                    if(stack.isEmpty()) return "NO";
                    char pop = stack.pop();
                    if(c == '}' && pop != '{'){
                        return "NO";
                    }
                    if(c == ')' && pop != '('){
                        return "NO";
                    }
                    if(c == ']' && pop != '['){
                        return "NO";
                    }
                }
            }
            
            if(stack.isEmpty()) return "YES";
            
            return "NO";
        }