Check Balanced Brackets
You get a string s. Every character in it is one of (, ), [, ], { or }.
Return true if the brackets are balanced, and false if they are not. The brackets are balanced when:
- every opening bracket is closed by a closing bracket of the same kind, and
- brackets are closed in the right order: the bracket opened last must be closed first, and
- no closing bracket appears without an opening bracket before it.
Note
An empty string has no brackets, so it is balanced. Return true for it.
Hint
Read the string from left to right and keep a stack of the opening brackets that are not closed yet. When you see a closing bracket, the top of the stack must be the matching opening bracket. At the end, the stack must be empty.
Examples
Example 1
- Input:
- "{[()()]}"
- Output:
- true
Each bracket is closed by the same kind, and the inner brackets close before the outer ones.
Example 2
- Input:
- "([)]"
- Output:
- false
The "[" is opened after the "(", so it must close first. But ")" comes before "]", so the order is wrong.
Example 3
- Input:
- "(()"
- Output:
- false
One "(" is never closed.
Constraints
0 <= s.length <= 40- Every character of
sis one of()[]{}.
Run checks your code against the 3 examples. Submit checks it against all 253 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.