How to check whether a String is a Balanced String or not ?

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this example, we are going to see how to check whether a String is a balanced string or not?
Input: ([{}{}{}]{})
Output: Given string is Balanced
Input: {}[}[}}
Output: Given string is Not Balanced

I am going to solve this problem by using ArrayDeque; we can also use Stack either.
Here I am sticking to (),[],{} characters, if you wish to have more characters you can free to add these characters into the logic.
I am adding all open symbols into an array.
Create a Map containing all corresponding open and close symbols.
Read String from System.in
Loop through each character from the String.
Check each character, whether it contained in open symbol array or not. If it does not contain, insert the symbol into it ArrayDequeue (Stores only open symbols).
So for a certain point in time, all the open symbols will sit into the ArrayDequeue.
Now for closed symbols (else case), pop each element from ArrayDqueue and get the corresponding popped element value from the open_close map. If the map doesn’t contain the value of the popped element, we can say the provided string is not balanced.
This loop will go through the end of the string length, so by the end of the loop, ArrayDeque should be empty, as we are popping for each iteration.
If it is not empty, we can also say that the provided string is not balanced.
Let’s see in practice.
import java.util.*;

public class BalancedString {
    private char smallOpen = '(';
    private char smallClose = ')';

    private char midOpen = '[';
    private char midClose = ']';

    private char bigOpen = '{';
    private char bigClose = '}';

    List<Character> openList = Arrays.asList(smallOpen, midOpen, bigOpen);
    Map<Character, Character> open_closeMap = new HashMap<>();

    {
        open_closeMap.put(smallOpen, smallClose);
        open_closeMap.put(midOpen, midClose);
        open_closeMap.put(bigOpen, bigClose);
    }

    public static void main(String[] args) {
        BalancedString balancedString = new BalancedString();
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any String..");
        String s = sc.nextLine();
        System.out.println(balancedString.isBalanced(s) ? "Given string is Balanced" : "Given string is Not Balanced");
    }

    public boolean isBalanced(String str) {
        Deque<Character> deque = new ArrayDeque<>();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (openList.contains(c)) {
                deque.push(c);
            } else {
                if (deque.isEmpty()) {
                    return false;
                }
                char pop = deque.pop();
                if (open_closeMap.get(pop) != c) {
                    return false;
                }
            }
        }
        return deque.isEmpty();
    }
}

([{}{}{}]{})
Given string is Balanced
Happy Learning 🙂

Java Program to Find the characters count in String
Java Program To  Count number of words in a String
Java Program for Reverse of String
How Java 8 Stream generate random String and Numbers
String sorting in Java
Java Program for String Sorting Example
Java Program for Check Octal Number
Java Program To check a number is prime or not ?
Java Program to Check the Number is Perfect or not ?
Java Program to Check a Number is Palindrome or not ?
C Program – Check a number is Palindrome or not
How to check whether a file exists python ?
Spring Boot Actuator Database Health Check
String in Switch in Java 7 Example
How to Convert Java String to Int

Java Program to Find the characters count in String
Java Program To  Count number of words in a String
Java Program for Reverse of String
How Java 8 Stream generate random String and Numbers
String sorting in Java
Java Program for String Sorting Example
Java Program for Check Octal Number
Java Program To check a number is prime or not ?
Java Program to Check the Number is Perfect or not ?
Java Program to Check a Number is Palindrome or not ?
C Program – Check a number is Palindrome or not
How to check whether a file exists python ?
Spring Boot Actuator Database Health Check
String in Switch in Java 7 Example
How to Convert Java String to Int
 


Δ
 Install Java on Mac OS
 Install AWS CLI on Windows
 Install Minikube on Windows
 Install Docker Toolbox on Windows
 Install SOAPUI on Windows
 Install Gradle on Windows
 Install RabbitMQ on Windows
 Install PuTTY on windows
 Install Mysql on Windows
 Install Hibernate Tools in Eclipse
 Install Elasticsearch on Windows
 Install Maven on Windows
 Install Maven on Ubuntu
 Install Maven on Windows Command
 Add OJDBC jar to Maven Repository
 Install Ant on Windows
 Install RabbitMQ on Windows
 Install Apache Kafka on Ubuntu
 Install Apache Kafka on Windows
 Java8 – Install Windows
 Java8 – foreach
 Java8 – forEach with index
 Java8 – Stream Filter Objects
 Java8 – Comparator Userdefined
 Java8 – GroupingBy
 Java8 – SummingInt
 Java8 – walk ReadFiles
 Java8 – JAVA_HOME on Windows
 Howto – Install Java on Mac OS
 Howto – Convert Iterable to Stream
 Howto – Get common elements from two Lists
 Howto – Convert List to String
 Howto – Concatenate Arrays using Stream
 Howto – Remove duplicates from List
 Howto – Filter null values from Stream
 Howto – Convert List to Map
 Howto – Convert Stream to List
 Howto – Sort a Map
 Howto – Filter a Map
 Howto – Get Current UTC Time
 Howto – Verify an Array contains a specific value
 Howto – Convert ArrayList to Array
 Howto – Read File Line By Line
 Howto – Convert Date to LocalDate
 Howto – Merge Streams
 Howto – Resolve NullPointerException in toMap
 Howto -Get Stream count
 Howto – Get Min and Max values in a Stream
 Howto – Convert InputStream to String