- 题目
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.
翻译:
给定一个包含‘(’和‘)’的字符串,找出最长的有效括号匹配子串的长度。 思路
这道题可以用一维动态规划逆向求解。假设输入括号表达式为String s,维护一个长度为s.length的一维数组dp[],数组元素初始化为0。 dp[i]表示从s[i]到s[s.length - 1]包含s[i]的最长的有效匹配括号子串长度。代码
class Solution {
public:
int longestValidParentheses(string s) {
int len = s.size();
if (len < 2)return 0;
vector<int> dp(len + 1, 0);
int ans = 0;
for (int i = len - 2; i >= 0; i--)
{
if (s[i] == '(')
if (s[i + 1] == ')')
dp[i] = (i == len - 2 ? 0 : dp[i + 2]) + 2;
else
{
int k = dp[i + 1] + 1 + i;//
if (k < len)
{
dp[i] = (s[k] == ')' ? 2 + dp[k + 1] + dp[i + 1]: 0) ;
}
}
ans = max(ans, dp[i]);
}
return ans;
}
};
- 总结
这道题花了很长时间。问题存在如下1,dp[i]代表的意义设计不合理:刚开始的时候将dp[i]定义为0~i-1中的最优解。但是这样设定以后,想了很久也无法找到递推式。正确的做法是将其设置为包含s[i]的最优解。2 思路不清晰,递推式总是错误。导致vs调试了好多遍,但是每次都有疏忽或错误,wrong answer了好多次。正确的做法是,递推式的逻辑一定要严谨,且自己要清晰,不要脑子里乱成一锅粥。