“Check if a string has balanced brackets — Java”
“Use a stack to check if a string has balanced opening and closing brackets. Handles parentheses, square brackets, and curly braces.”
A string has balanced brackets when every opening bracket — (, [, { — has a matching closing bracket in the correct order. Non-bracket characters are ignored.
For example:
”adf(aew)23[34]ade(we{wefave}qwef)ad[e[qew]]”→ balanced — brackets reduce to()[]({})[[]]”([)]”→ not balanced — brackets are interleaved”hello”→ balanced — no brackets at all
Approach
Use a Stack:
- Walk through each character in the string
- If it’s an opening bracket, push it onto the stack
- If it’s a closing bracket, pop the stack and check if the popped character is the matching opening bracket
- If the stack is empty when popping, or the brackets don’t match — it’s not balanced
- After the loop, the string is balanced only if the stack is empty
Solution
import java.util.Map;
import java.util.Stack;
public class BalancedString {
private static final Map<Character, Character> BRACKETS = Map.of(
‘)’, ‘(‘,
‘]’, ‘[‘,
‘}’, ‘{‘
);
public static boolean isBalanced(String input) {
Stack<Character> stack = new Stack<>();
for (char ch : input.toCharArray()) {
if (BRACKETS.containsValue(ch)) {
stack.push(ch);
} else if (BRACKETS.containsKey(ch)) {
if (stack.isEmpty() || stack.pop() != BRACKETS.get(ch)) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
String[] testCases = {
“adf(aew)23[34]ade(we{wefave}qwef)ad[e[qew]]”,
“([)]”,
“{[()]}”,
“(((“,
“”,
“hello”,
“({[]})”,
“[(])”,
};
for (String test : testCases) {
String label = test.isEmpty() ? “(empty)” : test;
System.out.printf(“%-50s → %s%n”, label, isBalanced(test) ? “balanced” : “NOT balanced”);
}
}
}
Output
adf(aew)23[34]ade(we{wefave}qwef)ad[e[qew]] → balanced
([)] → NOT balanced
{[()]} → balanced
((( → NOT balanced
(empty) → balanced
hello → balanced
({[]}) → balanced
[(]) → NOT balanced
How it works
The stack ensures brackets are closed in the correct order. When we encounter a closing bracket, the top of the stack must be its matching opening bracket — otherwise the string is unbalanced. An empty stack at the end confirms every opening bracket was matched.
Time complexity: O(n) — single pass through the string.
Space complexity: O(n) — worst case, all characters are opening brackets.
Download Source Code
Source code is available on GitHub.