Challenge: Bracket Checker
Completed
Read a line that may contain (), [], {} and other characters. Print balanced if every bracket is closed by the right partner in the right order, otherwise not balanced. Ignore other characters.
Input
One line of text.
Output
balanced or not balanced.
Example
Input
if (a[i] > {b}) { x = (y + z); }Output
balanced
Editor
Java
Hints
Push opening brackets. For a closing bracket, pop and check it's the partner.
At the end the stack must be empty.
Solution explanation
O(n) with a stack. Compilers do exactly this to check your code's brackets.
Show solution
import java.util.ArrayDeque;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
ArrayDeque<Character> stack = new ArrayDeque<Character>();
boolean ok = true;
for (char c : s.toCharArray()) {
if ("([{".indexOf(c) >= 0) {
stack.push(c);
} else if (")]}".indexOf(c) >= 0) {
char want = "([{".charAt(")]}".indexOf(c));
if (stack.isEmpty() || stack.pop() != want) {
ok = false;
break;
}
}
}
System.out.println(ok && stack.isEmpty() ? "balanced" : "not balanced");
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module