C++ String Exercises: Length of the longest valid parentheses substring
18. Length of the Longest Valid Parentheses Substring
Write a C++ program to find the length of the longest valid (correct-formed) parentheses substring of a given string.
Example-1:
Input: "[[]"
Output: 2
Note: The longest correct-formed parentheses substring is "[]".
Example-2:
Input: " [[]]]"
Output: 4
Note: The longest correct-formed parentheses substring is "[[]]".
Example-3:
Input: " ]]]][[[["
Output:
Note: No correct-formed parentheses substring.
Sample Solution:
C++ Code:
Sample Output:
Original Parentheses string: [[] Length of longest parentheses: 2 Original Parentheses string: [[]]] Length of longest parentheses: 4 Original Parentheses string: ]]]][[[[ Length of longest parentheses: 0
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C++ program to find the length of the longest valid (well-formed) parentheses substring using a stack.
- Write a C++ program that scans a string of parentheses and returns the length of the longest balanced substring.
- Write a C++ program to compute the maximum length of valid parentheses by iterating through the string with two counters.
- Write a C++ program that uses dynamic programming to determine the length of the longest valid parentheses sequence.
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous C++ Exercise: Combinations of brackets of pairs of parentheses.
Next C++ Exercise: Reverse only the vowels of a given string.What is the difficulty level of this exercise?