Balanced Parentheses
easySave
StackString
You need to write a function that will accept a string containing only the characters '(', ')', '{', '}', '[' and ']', 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.
- Every close bracket has a corresponding open bracket of the same type.
Example 1
Input
[ "()" ]
Output
true
Explanation. Simple balanced parentheses.
Example 2
Input
[ "()[]{}" ]
Output
true
Explanation. Multiple types of balanced parentheses.
Example 3
Input
[ "(]" ]
Output
false
Explanation. Parentheses are not correctly closed.
Example 4
Input
[ "([)]" ]
Output
false
Explanation. The order of parentheses closing is incorrect.
Example 5
Input
[ "{[]}" ]
Output
true
Explanation. Nested balanced parentheses.
Follow-up: Consider a follow-up where the input can include other characters, not just parentheses. How would you adapt your solution to handle this?
Constraints:
The input string will only contain the characters '(', ')', '{', '}', '[' and ']', and will not be empty.
- Views
- 3