Loading...
Loading...
A spreadsheet app checks formulas before running them. Brackets are balanced when every opening bracket (, [ or { is closed by the same kind, in the right order, and no bracket closes something that was never opened. Other characters are ignored. Read a formula and print Balanced or Not balanced. A formula with no brackets is balanced.
Balanced or Not balanced.Example 1
Input
{[()]}Output
Balanced
Example 2
Input
([)]
Output
Not balanced
The ( is closed by ] before the [ closes.
Try the problem first. Open one hint at a time.
The bracket that must close next is always the most recently opened one that is still open.
Keep the open brackets in a char[] used as a stack, with an int top for how many are stored.
On a closing bracket, the stack must not be empty and its top must be the matching opener; then remove it. At the end the stack must be empty.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor