Loading...
Loading...
Riya is building a formula checker for her college coding club. Before checking anything else, it looks only at the brackets of a formula: ( ), [ ] and { }.
The brackets are balanced when every opening bracket has a closing bracket of the same kind after it, and a bracket that opens later closes earlier. So {[()]} is balanced, but ([)] is not. Print YES if the line is balanced, otherwise NO.
(, ), [, ], { and }. There are no spaces.YES if the brackets are balanced, otherwise NO.Example 1
Input
{[()()]}Output
YES
Every bracket closes in the reverse order of opening, so the answer is YES.
Example 2
Input
([)]
Output
NO
The [ opened after (, so it must close first. Here ) comes first, so the answer is NO.
Try the problem first. Open one hint at a time.
The bracket that closes next must match the most recent bracket that is still open.
Keep the open brackets in a stack. Push every opening bracket.
For a closing bracket, the stack must not be empty, and the top must be the same kind. Then pop it.
At the end, the line is balanced only if nothing is left open.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor