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.
dp[i] 记录下标i 与其左边的串,往左能匹配的最大长度;
用栈记录(,遇到)则出栈,匹配出来的最大连续的串,一定是最唯一的也是最长的串!
dp[i] = stack.empty()? 0 :i - stack.top + 1 + dp[top - 1];stack为未匹配的(的栈,遇到(即入栈,遇到)出栈,
若栈空则dp[i] = 0即当前下标能往左匹配的最大连续长度为0,这里要注意若果top == 0 则dp[i] = i - stack.top + 1 +0;
因为0往左为空串,空串能匹配的长度肯定为0!
class Solution {
public:
int longestValidParentheses(string s) {
if(!s.size())return 0;
stack<int> stc;
int len = s.size();
int *dp = new int[len];
int rst = 0;
//对于括号匹配,用栈保存( 匹配,能获得的匹配结果,是唯一的连续的也是最长的能匹配的结果
for(int i = 0; i < len; i++)
{
if(s[i] == '(')
{
stc.push(i);
dp[i] = 0;
continue;
}
if(!stc.empty())
{
int idx = stc.top();
stc.pop();
//当前匹配的左括号所在位置的左边最大匹配,加上当前匹配的左括号的长度
dp[i] = i - idx + 1 + (idx == 0 ? 0 :dp[idx - 1]);
}
else
dp[i] = 0;
rst = max(rst, dp[i]);
}
return rst;
}
};

本文介绍了一种算法,用于在给定只包含'('和')'字符的字符串中找到最长的有效括号子串。通过使用动态规划和栈结构,实现了一种高效的方法来解决这一问题,并详细解释了算法的实现过程。
395

被折叠的 条评论
为什么被折叠?



