×

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

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

How to find the length of an Array in Java

Arrays: An array is a sort of container object that stores constant quantities of values of a single type in one memory area. A finite number of items must all be...

3 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.

How to Reduce Time Complexity in Java

What is time complexity?  The time complexity in java is given as the amount of time a program requires to run or execute it Calculating the time complexity of the program The time...

4 minutes read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.