×

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must determine whether or not the brackets in some kind of a given string are balanced.

Brackets include symbols like "(", "")", "[", "]", "," and "."

If the starting bracket appears to the left of the equivalent closing bracket, then the group of parentheses is said to be matched.

Bracket pairs really aren't balanced if the brackets enclosing a string are still not matched.

A string that contains non-bracket characters like a-z, A-Z, 0-9, as well as other special characters like #, $, and @ is likewise regarded as unbalanced in this way.

Example “{[(])}”

The two round brackets, "()," encompass a single unbalanced closing square parenthesis, "]," and the two square brackets, "[]," surround a single unbalanced starting round bracket, "(," making it an imbalanced input string.

A bracketed string is considered to also be balanced if:

  • Each equivalent opening bracket is followed by a matched closing bracket.
  • Balanced brackets also should enclose balanced brackets.
  • There shouldn't be any non-bracket characters in it.

Note 1: Null is thought to be in balance.

Note 2: A string that is empty is thought to be balanced.

Algorithm (Deque)

  • We create a character stack first.
  • input string to character array conversion.
  • Explore the input string (By traversing the character array).
    • If the current character is a starting bracket ('(', ", or '['), we push it to the stack.
    • If the current character is a closing bracket, we pop it off the stack. The brackets are not balanced if the character that pops out doesn't match the initial bracket.
  • The brackets really aren't balanced once the traversal is complete, and some initial brackets are still present in the stack.

Stack, Deque, and a straightforward for loop can be used to build the code with balanced parentheses.

BalancedParenthesesExpl1.java

// import any necessary packages and classes.   
import java.util.*;   
// To implement Balanced Parentheses using stack, 
// create the class BalancedParenthesesExpl1.
public class BalancedParenthesesExpl1 {   
      // develop a balanced approach 
// To determine whether the supplied 
// string is balanced, use the function parenthesis(). 
    @SuppressWarnings({ "rawtypes", "unchecked" })   
    public static boolean balancedParenthesis(String inputStr) {   
          
        // creating an empty stack   
        Stack st = new Stack();   
          
        // convert inputStr to char arr   
        char[] charArr = inputStr.toCharArray();   
          
        // iterate charArr   
        for (int j = 0; j < charArr.length; j++) {   
              
            // get c   
            char c = charArr[j];   
              
            // check to see whether c is "(," "[," or ""  
            if (c == '{' || c == '[' || c == '(') {   
                // push current to stack   
                st.push(c);   
                continue;   
            }   
            // Return false if the stack is empty.   
            if (st.isEmpty()) {    
                return false;   
            }   
              
            // Use a switch statement to remove an element 
// from the stack, and return false if the element is '(', '[', or ". 
            char pC;   
            switch (c) {   
                case ')':   
                pC = (char) st.pop();   
                if (pC == '{' || pC == '[')   
                    return false;   
                break;   
                case '}':   
                pC = (char) st.pop();   
                if (pC == '(' || pC == '[')   
                    return false;   
                break;   
                case ']':   
                pC = (char) st.pop();   
                if (pC == '(' || pC == '{')   
                    return false;   
                break;   
            }   
        }   
        return (st.isEmpty());   
    }   
    // driver code   
    public static void main(String[] args) {   
          
        String iS;   
          
        // create an object for the Scanner class   
        Scanner s = new Scanner(System.in);   
         System.out.println("Enter input string to check:");   
        // taking the input string from the user   
        iS = s.nextLine();   
          
        // To determine whether the supplied string
//  is balanced or not, call the balancedParenthesis() function.   
        if (balancedParenthesis(iS))   
            System.out.println(" Given Input string "+iS+" is balanced.");   
        else   
            System.out.println(" Given Input string "+iS+" is not balanced.");   
    }   
}  

Output:

Balanced Parentheses in Java

BalancedParenthesesExpl2.java

// import any necessary packages and classes.    
import java.util.Scanner;   
   
// To implement Balanced Parentheses using simple for loop, 
// create the class BalancedParenthesesExpl2.
public class BalancedParenthesesExpl2 {   
    // driver code   
    public static void main(String[] args)   
    {   
        String iS;   
        int j, l, k=0, c=0;   
        char crr, ch;   
          
        // creating an empty stack   
        char[] st = new char[20];   
          
        // create an object for the Scanner class   
        Scanner s = new Scanner(System.in);   
          
        System.out.print("Enter an expression to check whether it is balanced or not: \n");   
        iS = s.nextLine();   
          
        // closing Scanner class instance   
        s.close();   
          
        // get length of iS  
        l = iS.length();   
          
        // using for loop to iterate the input string   
        for(j = 0; j < l; j++) {   
              
            crr = iS.charAt(j);   
              
            // check whether crr is '(', '{', or '['   
            if(crr =='(' || crr =='{' || crr =='[') {   
                st[k] = crr;   
                k++;    // increase the count of k   
                c = 1;  // set c to 1   
            } else if(crr == ')') {     // if crr char is ')'   
                if(c == 1) // if c is 1, decrement count of k   
                    k--;   
                ch = st[k];  // store st[k] to ch   
                if(st.length == 0 || ch != '(') {    // Parentheses are not balanced if st is empty while ch is opening with the letter "("   
                    System.out.println("\nUnbalanced Parentheses!");   
                    return;   
                }   
            } else if(crr == '}') { // if crr char is '}'   
                if(c == 1)  // if c is 1, decrement the count of k 
                    k--;   
                ch = st[k];  // store st[k] to ch   
                if(st.length == 0 || ch != '{') {    // Parentheses are not balanced if st is empty while ch is opening with the letter "{"  
                    System.out.println("\nUnbalanced Parentheses!");   
                    return;   
                }   
            } else if(crr == ']') { // if curr char is ']'   
                if(c == 1)  // if c is 1, decrement the count of k  
                    k--;   
                ch = st[k];  // store st[k] to ch   
                if(st.length == 0 || ch != '[') {    // Parentheses are not balanced if stack is empty while ch is opening with the letter "[" 
                    System.out.println("\nUnbalanced Parentheses!");   
                    return;   
                }   
            }   
        }   
          
        System.out.println("\nBalanced Parentheses.");   
    }   
}   

Output:

Balanced Parentheses in Java

BalancedParenthesesExpl3.java

// import any necessary packages and classes.  
   
import java.util.Deque;   
import java.util.LinkedList;   
import java.util.Scanner;   
   
// To implement Balanced Parentheses using Deque, 
// create the class BalancedParenthesesExpl2. 
public class BalancedParenthesesExpl3 {   
    // Driver Code   
    public static void main(String[] args)   
    {   
        String iS;   
          
        // creating an empty deque using LinkedList   
        Deque<Character> dq = new LinkedList<>();   
          
        // create an object for the Scanner class   
        Scanner s = new Scanner(System.in);   
          
        System.out.print(" To determine whether an expression is balanced, enter one:\n ");   
        iS = s.nextLine();   
          
        // closing the Scanner class instance   
        s.close();   
          
        // iterating through the input string using for loop   
        for(char ch : iS.toCharArray()) {   
            // add elements to dq if ch = '{', ch = '[', or ch = '('   
            if(ch == '{' || ch == '[' || ch == '(') {   
                dq.add(ch);   
            } else {   
                // if dq is not empty   
                if(! dq.isEmpty()) {   
                    if((dq.peekFirst() == '{' && ch == '}')   
                       || (dq.peekFirst() == '[' && ch == ']')   
                       || (dq.peekFirst() == '(' && ch == ')')) {   
                           dq.removeFirst();   
                       }   
                }else {   
                    System.out.println("\nUnbalanced Parentheses.");   
                }   
            }   
        }   
        System.out.println("\nBalanced Parentheses.");   
    }   
}   

Output:

Balanced Parentheses in Java

Related Topics

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

How to Convert String to char in Java

How to Convert String to char in Java There are two methods to convert String to char are: Using charAt() method Using tocharArray() method Using charAt() method This is the method of String class that...

3 minutes read.

Java Integer equals() method

The equals() method of Integer class compares the given object to the specified object. Syntax public boolean equals(Object obj) Parameters The parameter ‘obj’ represents the object to be compared with. Overrides The equals() method overrides equals...

1 minute read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Cyclic Barrier in Java

Programmers often find it challenging to run multiple threads simultaneously. Java introduces the idea of concurrency, which enables us to run many threads concurrently, making this work simpler. Concurrent programming...

6 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Java String startsWith() method

Java String startsWith() method checks whether current String starts with given prefix or not . Syntax: public boolean startsWith(String prefix) public boolean startsWith(String prefix, int offset) Parameters: prefix : It is sequence of character Returns: It returns...

2 minutes read.

Various Operation on Queue using Linked List in Java

We keep track of front and rear pointers in a queue data structure. The head of the line points to the first item, and the back to the last. Rear is...

3 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.