Longest Valid Parentheses
Posted: 11 Jan, 2021
You are given a string ‘S’ containing only the characters ‘)’ and ‘(‘. You need to find the length of the longest valid i.e. well-formed parentheses substring.
Let the given string be “(()())((”. Here the valid parentheses substrings are: “()”, “()” and “(()())”. Out of these the longest valid string is “(()())” which has a length 6.
The first line of input contains an integer ‘T’ representing the number of test cases. The first and the only line of every test case contains the string S.
For each test case, the length of the longest valid (well-formed) parentheses substring is printed. The output for each test case is printed in a separate line.
You don’t need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 100 1 <= Length(S) <= 10^4 Where ‘T’ is the number of test cases and ‘S’ is the given string. Time Limit: 1sec
- The idea is to generate all the possible substrings of the given string.
- For each substring check if it is valid or not.
- This can be checked by using a stack.
- If it is valid, check if its length is greater than the previously generated valid substrings. If so, update the maximum length.
- Return the length of the longest substring.
The algorithm for the above approach is:
- Generate a substring SUB of the given string.
- Now we need to check if SUB is valid or not. For this, create an empty stack.
- Iterate over the substring:
- If the current character is ‘(‘, Push it in the stack.
- Otherwise, If the current character is ‘)’
- If the stack is empty, SUB is invalid.
- Otherwise, Pop an element from the stack.
- After step 3, if the stack is NOT empty, SUB is invalid.
- Otherwise, SUB is valid, update the maximum length if required.
- Repeat the above procedure until all the substrings have been checked.