Java Program to Check Balanced Parentheses

 

 

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.

 

Leave a Reply

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