Challenge: Balanced Brackets
Completed
Read one line made of the brackets ( ) [ ] { }. Print balanced if every opening bracket is closed by the right kind in the right order, otherwise not balanced. Use a stack.
Input
One line of brackets.
Output
balanced or not balanced.
Example
Input
([]{})Output
balanced
Editor
C++
Hints
Push every opening bracket.
For a closing bracket, the top of the stack must be its matching opener: then pop.
At the end the stack must be empty.
Solution explanation
The most recent unclosed bracket is always on top of the stack, which is exactly the one the next closing bracket must match.
Show solution
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
string s;
getline(cin, s);
stack<char> open;
bool ok = true;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
open.push(c);
} else if (c == ')' || c == ']' || c == '}') {
char want = (c == ')') ? '(' : (c == ']') ? '[' : '{';
if (open.empty() || open.top() != want) {
ok = false;
break;
}
open.pop();
}
}
if (!open.empty()) ok = false;
cout << (ok ? "balanced" : "not balanced") << "\n";
return 0;
} 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