Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding
Ninjas X Naukri.com

Problem of the day

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.
```

Detailed explanation

```
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
```

```
2
)()()))
)))(((
```

```
4
0
```

```
For the first test case, the longest valid (well-formed) parentheses substring is “()()” with length 4.
For the second test case, there is no valid parentheses substring. Hence, the output is 0.
```

```
2
()((())()
()()()()()()()
```

```
6
14
```