Balanced Brackets
Given a string containing only the characters (, ), {, }, [, and ], determine if the input string is valid. An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- No unmatched brackets should remain.
[ "()" ]
Explanation. The parentheses are matched and closed in the correct order.
[ "()[]{}" ]
Explanation. All types of brackets are matched and closed correctly.
[ "(]" ]
Explanation. The parenthesis is closed with a bracket, which is incorrect.
[ "([)]" ]
Explanation. The brackets are not closed in the correct order.
[ "{[]}" ]
Explanation. All brackets are matched and closed correctly, in the proper nested order.
Follow-up: Could this problem be solved using another data structure? What would be the advantages and disadvantages?
1. The length of the input string is between 1 and 1000. 2. Only the characters `(`, `)`, `{`, `}`, `[`, and `]` are allowed in the input string.
- Views
- 4