Balanced Delimiters
easySave
StackString
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
- Open brackets are closed by the same type of brackets.
- Open brackets are closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Example 1
Input
[ "()" ]
Output
true
Explanation. The parentheses are balanced.
Example 2
Input
[ "()[]{}" ]
Output
true
Explanation. All types of brackets are correctly balanced.
Example 3
Input
[ "(]" ]
Output
false
Explanation. The parentheses are closed in the incorrect order.
Example 4
Input
[ "([)]" ]
Output
false
Explanation. The brackets are not closed in the correct order.
Example 5
Input
[ "{[]}" ]
Output
true
Explanation. All types of brackets are balanced and closed correctly.
Example 6
Input
[ "" ]
Output
true
Explanation. An empty string is trivially balanced.
Follow-up: Can you extend the solution to include other types of brackets or delimiters?
Constraints:
The input string will only contain the characters '(', ')', '{', '}', '[' and ']', and can be empty.
- Views
- 2