Count Valid Parentheses Strings
Given a string containing only the characters ( and ), count how many segments of the string form a valid parentheses combination. A valid parentheses combination means that each opening parenthesis ( has a corresponding closing parenthesis ) and they are in the correct order.
[ "()" ]
Explanation. There is 1 valid segment `()`, which is a valid parentheses combination.
[ "())" ]
Explanation. The segment `()` is valid but `)` is not paired, so there is only 1 valid segment.
[ "(())" ]
Explanation. The segment `(())` is valid as both pairs of parentheses close correctly.
[ "()()" ]
Explanation. There are two valid segments `()` and `()`.
[ "((()))" ]
Explanation. The segment `((()))` includes nested valid pairs, forming one complete valid segment.
[ "((())())" ]
Explanation. The segments `(())` and `()` both form valid parentheses combinations, totaling two.
Follow-up: How would you modify your solution if the string could include other characters such as `{}` and `[]` and you need to validate combinations of all these types?
The input string will only contain the characters `(` and `)`. The string will not exceed 100 characters in length.
- Views
- 2