
1. Overview
In this article, we will learn to check for the balanced parentheses in Java. To learn more about Java, refer to these articles.
2. Check for balanced parentheses or brackets in Java
A bracket can be any of the characters: ()
round brackets, []
square brackets, {}
curly brackets.
You can consider the bracket as balanced if the opening bracket (, [, or { appears to the left of a closing bracket ), ], or } of the exact same type. There are three types of balanced pairs of brackets: [], {}, and ()
.
A matching pair of brackets is not balanced if the set of brackets it encloses are not matched.
For example, {[(])}
is not balanced because the contents in between {
and }
are not balanced. The pair of square brackets enclose a single, unbalanced opening bracket (
and the pair of parentheses enclose a single unbalanced closing square bracket ]
.
Given n strings of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, return true
. Otherwise, return false
.
import java.util.*; public class ParenthesesValidation { static boolean areBalancedBrackets(String expr) { // You can use ArrayDeque as Stack or Queue. Deque<Character> stack = new ArrayDeque<Character>(); char[] exprArr = expr.toCharArray(); for (int i = 0; i < exprArr.length; i++) { char x = exprArr[i]; // put to the stack if it is open parentheses if (x == '(' || x == '[' || x == '{') { // Push the element in the stack stack.push(x); continue; } // the stack doesn't have any opening parentheses // for example: }{ // this starts with closing parentheses and no open parentheses so fail and return false if (stack.isEmpty()) return false; char current = stack.pop(); switch (x) { case ')': if (current == '{' || current == '[') return false; break; case '}': if (current == '(' || current == '[') return false; break; case ']': if (current == '(' || current == '{') return false; break; } } // if stack not empty then there is unbalanced parentheses return (stack.isEmpty()); } }
You can use the above class to check whether the brackets are balanced.
public static void main(String[] args) { String expr = "({[]})"; if (areBalancedBrackets(expr)) System.out.println("Balanced "); else System.out.println("Not Balanced "); }
3. Conclusion
To sum up, we have learned to check for the balanced brackets in a Java string. You can find code samples in our GitHub repository.