-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path32. Longest Valid Parentheses
42 lines (35 loc) · 1.04 KB
/
32. Longest Valid Parentheses
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
class Solution {
public:
int longestValidParentheses(string s) {
stack<char> s1; //to store the character
stack<int> s2; //to store the invalid character index
s2.push(-1);
int maxi = 0;
for(int i=0; i<s.length(); i++)
{
//we consider first opening bracket is a problem character //because we assume that we can't get it's pair(closing barcket)
if(s[i] == '(')
{
s1.push(s[i]);
s2.push(i);
}
else
{
//if character stack is empty means that is a problem character
if(s1.empty())
{
s2.push(i);
}
else //we get a pair
{
s1.pop();
s2.pop();
int a = s2.top();//last problem index
if(i-a > maxi) //calculate the maximum length
maxi = i - a;
}
}
}
return maxi;
}
};