您的位置:首页 > 其它

32. Longest Valid Parentheses

2017-02-24 09:05 344 查看
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.

Subscribe to see which companies asked this question.

找到最长的有效的括号对子字符串。对一个右括号')',有效的情况是,它的左边是一个左括号'(',或者是一个有效的括号对子字符串,然后该子字符串的左边是左括号'('。用数组保存包含每个位置且以该位置为结尾的有效的括号对子字符串的长度。对每个右括号,左括号或许在它的左边,或许在它左边的有效括号对子字符串的左边,如果找到计算它与对应的左括号之间的距离(包括两个括号),如果这对括号的左边还是有效的括号对子字符串,就连接上,将子字符串长度保存在数组的对应位置上。求子字符串长度的最大值即可。

代码:
class Solution
{
public:
int longestValidParentheses(string s)
{
int i = 0, res = 0, cnt = 0, n = s.size();
vector<int>len(n, 0);

while(s[i++] == ')');
for(i; i < n; ++i)
{
if(s[i] == ')')
{
if(i == 1)
{
len[i] = 2;
}
else
{
if(i - 1 - len[i-1] >= 0 && s[i - 1 - len[i-1]] == '(')
{
len[i] = 2 + len[i-1];
}
else
{
len[i] = 0;
}
}
if(len[i - len[i]] > 0) len[i] += len[i - len[i]];
res = max(res, len[i]);
}
}

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