Longest Valid Parentheses

Desicription

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

Solution

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
class Solution {
public:
int longestValidParentheses(string s) {
stack<int>Q;
for(int i = 0; s[i]; i++){
if(Q.empty())
Q.push(i);
else{
if(s[Q.top()] == '(' && s[i] == ')')
Q.pop();
else
Q.push(i);
}
}
if(Q.empty())
return s.length();
int res = 0;
int right = s.length();
int left = 0;
while(!Q.empty()){
left = Q.top();
Q.pop();
res = max(res, right - left - 1);
right = left;
}
res = max(res, right);
return res;
}
};