Stack: are the brackets balanced
Read one line of brackets (( ) [ ] { }) and use a stack to decide whether they are balanced. Print 1 if balanced, 0 otherwise. The empty string is balanced.
This is the classic stack use. Complete isBalanced:
- On an opening bracket
([{→ push. - On a closing bracket → check the top is the matching opener: if so pop, otherwise (or if the stack is empty) it is unbalanced.
- After processing everything, the stack must be empty to be balanced.
Pitfalls (straight from the bug lab): (1) on a closing bracket with an empty stack, it is immediately unbalanced (do not pop an empty stack). (2) Check the type matches (
]needs[, not(). (3) Don't forget the final empty check —(((never hits a mismatch but the stack isn't empty, so it's unbalanced.
Input
- One line: the bracket string (may be an empty line).
Output
- One line:
1(balanced) or0(not).
Example: input ([]) -> 1; input ([)] -> 0.