forked from tarunsinghofficial/HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest-Valid-Parenthesis.cpp
63 lines (59 loc) · 1016 Bytes
/
Longest-Valid-Parenthesis.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <string>
using namespace std;
int main() {
//code
string s;
int T, i, j;
cin>>T;
int maxl, left, right, leftj, rightj ;
while(T--)
{
cin>>s;
maxl = 0;
left = 0;
right = 0;
leftj = 0;
rightj = 0;
for(i=0, j=s.size()-1; i<s.size(), j>=0; i++, j--)
{
if(s[i]=='(')
{
left++;
}
else
{
right++;
}
if(left==right)
{
maxl = max(maxl, 2*left);
}
else if(right>left)
{
right = 0;
left = 0;
}
if(s[j]=='(')
{
leftj++;
}
else
{
rightj++;
}
if(leftj==rightj)
{
maxl = max(maxl, 2*leftj);
}
else if(rightj<leftj)
{
rightj = 0;
leftj = 0;
}
}
cout<<maxl<<endl;
s.clear();
}
return 0;
}