题目
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: “(()”
Output: 2
Explanation: The longest valid parentheses substring is “()”
Example 2:
Input: “)()())”
Output: 4
Explanation: The longest valid parentheses substring is “()()”
算法思路
本周学习动态规划的问题,本题就是动态规划思想的一个很好的实践。
这道题要求最长的有效括号字符串。首先我们可以得出的事实是有效括号字符串一定以“(”开头,以“)”结尾,根据这个性质,我们可以确定在何处开始识别一个有效的括号字符串。我们以“)”为例,设置一个“)”的个数长度的数组size,保存以当前的“)”结尾的最长的有效括号字符串。把问题分解为求不同位置上的最优解。然后遍历字符串,在遇到第i个“)”执行更新操作
- 第i-1个字符为“(”时,设置size[i] = 2,表示长度为2的有效字符串,如果本串前面邻接有有效字符串,则要相加。
- 第i-1个字符为“)”时,如果i-1是某个有效字符串的一个结尾,而且第i个字符能与该串前面一个字符闭合,则设置size[i] = size[i-1]+2,组成一个新的有效长串,如果该串前面邻接有有效串,则要相加。
C++代码
class Solution {
public:
int longestValidParentheses(string s) {
if (s.size() == 0)
{
return 0;
}
int size[s.size()] = {0};
for (int i = 1; i < s.size(); ++i)
{
if (s[i] == ')')
{
if (s[i-1] == '(')
{
size[i] = 2;
if (i - 2 >= 0)
{
size[i] += size[i-2];
}
}
else if (i - size[i-1] - 1 >= 0 && s[i - size[i-1] - 1] == '(')
{
size[i] = size[i-1] + 2;
if (i - size[i-1] - 2 >= 0)
{
size[i] += size[i - size[i-1] - 2];
}
}
}
}
int result = 0;
for (int i = 0; i < s.size(); ++i)
{
if (size[i] > result)
{
result = size[i];
}
}
return result;
}
};