Balanced delimiters
A config linter walks a snippet and rejects it if the brackets, braces and parentheses do not nest cleanly.
- Only the characters ( ) [ ] { } matter; everything else is ignored.
- Every opener must have a matching closer of the same kind, in the right order.
- An empty snippet — or one with no brackets at all — is fine.
balancedDelimiters(text: string) → bool
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
boolean balancedDelimiters(String text) {
}
Worked examples
| Call | Result |
|---|---|
balancedDelimiters("()") | true |
balancedDelimiters("([])") | true |
balancedDelimiters("(]") | false |
balancedDelimiters("[(])") | false |
Hint
Push each opener, and when a closer arrives the top of the stack must be its matching opener.
Reference solution in Java
boolean balancedDelimiters(String text) {
Deque<Character> expect = new ArrayDeque<>();
for (char ch : text.toCharArray()) {
if (ch == '(') expect.push(')');
else if (ch == '[') expect.push(']');
else if (ch == '{') expect.push('}');
else if (ch == ')' || ch == ']' || ch == '}') {
if (expect.isEmpty() || expect.pop() != ch) return false;
}
}
return expect.isEmpty();
}