0%

LeetCode: 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
class Solution {
public:
int longestValidParentheses(string s) {
if(s.length()<2)
return 0;
int ret=0;
vector<int> dp(s.length(),0);
for(int i=1;i<s.length();++i)
{
if(s[i]=='(')
continue;
else
{
if(s[i-1]=='(')
{
dp[i]=i>1?(dp[i-2]+2):2;
}
else{
if(i-dp[i-1]-1>=0 && s[i-dp[i-1]-1]=='(')
{
dp[i]=dp[i-1]+2+((i-dp[i-1]-2)>=0?dp[i-dp[i-1]-2]:0);
}
}
}
ret=max(ret, dp[i]);
}
return ret;
}
};