You are given a string 'STR' consisting only of opening and closing parenthesis i.e. '(' and ')', your task is to find out the length of the longest valid parentheses substring.
Note:The length of the smallest valid substring '()' is 2.
For example:
'STR' = “()()())” here we can see that except the last parentheses all the brackets are making a valid parenthesis. Therefore, the answer for this will be 6.
The first line of input contains an integer 'T' denoting the number of test cases.
The first and the only line of each test case contains a string ‘str’ of which you have to tell the longest valid parentheses substring.
Output format :
For each test case, return a single integer which is the length of the longest valid substring.
Note:
You don’t have to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= |STR| <= 3000
where |STR| is the length of the given string.
Time Limit: 1 sec
2
()))((())
))((
4
0
For the first test case:
Given 'STR' =”()))((())”, we can see that from index 5 to the last, the whole substring is valid. Therefore, the length of the longest valid parentheses substring is 4.
For the second test case:
Given 'STR' =”))((”, we can see that there is no valid substring present in the string. o, the answer will be 0.
2
()))((((())))))
)(()
10
2
Can you check for all the possible substrings?
The idea is to check for all the substrings of the given string and then check for each substring whether it is valid or not.
O(N ^ 3), where ‘N’ denotes the length of the given string.
Since we are calculating all possible substrings of the string and then we are calculating the validity of each substring. So, the time complexity will be O(N ^ 3)(for calculating every substring) + O(N)(for its validity) = O(N ^ 3).
O(N), where ‘N’ denotes the length of the given string.
Since we are using a stack for storing the string characters, the net space complexity will be O(N).