32. Longest Valid Parentheses
2017-02-24 09:05
344 查看
Given a string containing just the characters
find the length of the longest valid (well-formed) parentheses substring.
For
which has length = 2.
Another example 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;
}
};
'('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;
}
};
相关文章推荐
- LeetCode 32. Longest Valid Parentheses(hard)
- [leetcode] 32. Longest Valid Parentheses 解题报告
- [leetcode] 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 【栈/DP】LeetCode 32. Longest Valid Parentheses 八种解法
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 【LeetCode】32. Longest Valid Parentheses (2 solutions)
- 32. Longest Valid Parentheses
- LeetCode Algorithms 32. Longest Valid Parentheses
- 【C++】 LeetCode 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- LeetCode 32. Longest Valid Parentheses(最长有效括号)
- 32. Longest Valid Parentheses
- leetcode 32. Longest Valid Parentheses 最长有效括号长度
- 32. Longest Valid Parentheses
- [LeetCode]32. Longest Valid Parentheses
- 个人记录-LeetCode 32. Longest Valid Parentheses