• + 0 comments
    public static String isBalanced(String s) {
        // Use ArrayDeque instead of Stack for better performance
        Deque<Character> stack = new ArrayDeque<>();
    
        for (char ch : s.toCharArray()) {
            // Push opening brackets onto the stack
            switch (ch) {
                case '(':
                case '[':
                case '{':
                    stack.push(ch);
                    break;
                default: 
                    // If the stack is empty or brackets don't match, return "NO"
                    if (stack.isEmpty() //
                        || !isMatchingPair(stack.pop(), ch)) {
                        return "NO";
                    }
                    break;
            }
        }
        // If the stack is empty, the string is balanced
        return stack.isEmpty() ? "YES" : "NO";
    }
    
    // Helper method to check if brackets match
    private static boolean isMatchingPair(char open, char close) {
        return (open == '(' && close == ')') //
            || (open == '[' && close == ']') //
            || (open == '{' && close == '}');
    }