You are given a string STR containing just two characters ‘(‘ and ‘)’. You have to find the length of the longest balanced substring in the given string. String ‘B’ is a substring of string ‘A’ if it can be obtained from ‘A’ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters ‘+’ and ‘1’. For example, sequences ‘(())()’, ‘()’ and ‘(()(()))’ are balanced, while ‘)(‘, ‘(()’ and ‘(()))(‘ are not.
The first line of input contains a single integer T, representing the number of test cases or queries to be run. Then the T test cases follow.
The first line and only line of each test case contain a string STR containing just two characters ‘(‘ and ‘)’.
Output Format :
For every test case, print an integer denoting the length of the longest balanced substring.
The output of each test case is printed in a separate line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= |STR| <= 5 * 10^4
Where |STR| is the length of the string.
Time Limit: 1 sec
2
))(())
()()()
4
6
In the 1st test case, “(())” is the longest substring that is balanced.
In the 2nd test case, the whole string is balanced.
2
()(())
()
6
2
For each substring, check if it can be the longest balanced substring.
In this approach, we will consider every substring and check if it can be the longest balanced substring.
Below is the detailed approach:
To check if a string is balanced or not, follow the below steps:
O(N^3), Where N is the length of the given string.
It takes O(N^2) to consider every substring and in the worst case, it will take O(N) time to check if a substring is balanced or not. Thus, the final time complexity is O(N * N * N) = O(N^3).
O(1)
Constant additional space is required.