This code checks if a given string of brackets (e.g.,...

August 17, 2025 at 05:25 PM

import java.util.*; public class BalancedBrackets { public static void main(String[] args) { String str = "{[()]}"; // Test string if (isBalanced(str)) { System.out.println("Balanced"); } else { System.out.println("Not Balanced"); } } public static boolean isBalanced(String s) { Stack<Character> stack = new Stack<>(); for (char ch : s.toCharArray()) { // Push opening brackets if (ch == '(' || ch == '{' || ch == '[') { stack.push(ch); } // For closing brackets → check match else if (ch == ')' || ch == '}' || ch == ']') { if (stack.isEmpty()) return false; // no match char top = stack.pop(); if ((ch == ')' && top != '(') || (ch == '}' && top != '{') || (ch == ']' && top != '[')) { return false; } } } // If stack empty → all matched return stack.isEmpty(); } }

This code checks if a given string of brackets (e.g., "{[()]}") is balanced or not. A string of brackets is considered balanced if each opening bracket has a corresponding correctly ordered and properly nested closing bracket. Here's how the code works:

Details of the code logic:

  1. Input:

    • The function checks a string of brackets, such as "{[()]}" or "{{[[(())]]}}". Any combination of {, [, ( and their corresponding closing brackets can be checked.
  2. isBalanced Method:

    • Stack Usage:
      A stack is used to store opening brackets ({, [, (). Stacks follow a Last-In-First-Out (LIFO) approach, making them ideal for managing nested structures like balanced brackets.
    • Iterating Through the Characters:
      The code iterates over each character of the input string:
      • Opening Brackets: Push to the stack.
      • Closing Brackets: Check if it matches the most recent opening bracket (i.e., the top of the stack). If it matches, pop the stack. If not, the string is not balanced.
        • For example:
          • A closing ) must match an opening (.
          • A closing } must match an opening {.
          • A closing ] must match an opening [.
    • If at the end of the iteration the stack is empty, the string is balanced.
  3. Balanced or Not:

    • If the given string is fully processed and the stack is empty, the string is balanced (all brackets match).
    • If the stack is not empty (i.e., there are unmatched opening brackets) or if a closing bracket doesn't match during processing, the string is not balanced.
  4. Output:
    The program prints "Balanced" to the console if the string is balanced and "Not Balanced" if it's not.


Example Execution:

  • Input: "{[()]}"

    • The sequence of operations on the stack:
      1. { → Push (stack: [).
      2. [ → Push (stack: {[).
      3. ( → Push (stack: {[().
      4. ) → Matches with ( (pop stack, now stack: {[).
      5. ] → Matches with [ (pop stack, now stack: {).
      6. } → Matches with { (pop stack, now stack is empty).
    • Result: Balanced.
  • Input: "{[(])}"

    • The sequence will break at step 4 because ) does not match [.
    • Result: Not Balanced.

Key Features:

  • Handles multiple nested and adjacent brackets.
  • Supports validation for {}, [], and ().
  • Uses a stack-based approach for efficient bracket matching.
Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node