This program demonstrates how to check if a string containing different types of parentheses (i.e., ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘, ‘]’) is balanced. A balanced string has matching opening and closing parentheses, properly nested and ordered.

Program Structure

  • isBalanced Method: This method takes a string and returns true if the parentheses are balanced and false otherwise.
  • Main Method: Demonstrates the functionality by checking several strings.

Java Code

import java.util.Stack;

public class BalancedParentheses {
    public static boolean isBalanced(String s) {
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            } else if (c == ')' && !stack.isEmpty() && stack.peek() == '(') {
                stack.pop();
            } else if (c == '}' && !stack.isEmpty() && stack.peek() == '{') {
                stack.pop();
            } else if (c == ']' && !stack.isEmpty() && stack.peek() == '[') {
                stack.pop();
            } else {
                return false;
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        String[] tests = {"(()){}[]", "(({})", "({[]})", "(){}[]", "(]"};
        for (String test : tests) {
            System.out.println("Is \"" + test + "\" balanced? " + isBalanced(test));
        }
    }
}

Explanation of How the Program Works

  1. isBalanced Method: Iterates through each character in the string, pushing opening parentheses onto a stack and popping them when a matching closing parenthesis is encountered.
  2. Error Checking: Checks for mismatches or unmatched closing parentheses immediately return false.
  3. Final Check: After processing all characters, if the stack is empty, then all opening parentheses were matched and the string is balanced.

Key Components:

  • isBalanced Method: Main logic to check balance using a Stack<Character> to track opening parentheses.
  • Main Method: Used for demonstrating and testing the isBalanced method with various strings.

This approach offers an O(n) time complexity, where n is the number of characters in the string, because it involves a single pass through the string and constant-time operations with the stack. This solution is commonly used in compilers and text editors to validate the syntax.

Conclusion

This method efficiently checks for balanced parentheses using a stack to ensure that each opening parenthesis has a corresponding closing match. This is crucial for many applications in computer science, such as compiler syntax checking and evaluating expressions.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)