您的位置:首页 > 其它

leetcode 032 —— Longest Valid Parentheses

2015-07-14 21:30 459 查看
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.

思路:普通求解会超时,采用动态规划,动态数组d[i] 表示从i开始的最长有效字符串

class Solution {
public:
int longestValidParentheses(string s) {
int n = s.size();
int *d = new int
;
int max=0;
for (int i = 0; i < n; i++)
d[i] = 0;
for (int i = n - 2; i >= 0; i--){
if (s[i] == '('){
int j = i + 1 + d[i + 1];
if (j<n&&s[j] == ')'){
d[i] = d[i + 1] + 2;
if (j + 1 < n){
d[i] += d[j + 1];
}

}
max = max > d[i] ? max : d[i];
}
}
return max;
}
}a;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: