问题描述:
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 “()()”
题源:here;完整代码:here
思路:
两种方案:1 动态规划;2 使用堆栈。
方案1
动态规划最重要的是转移条件。设有如下变量:
record:记录每个位置的有效符号个数
s:输入字符串
我们首先将record全部置零,然后定义转移条件:
if s[i] == ‘)’ and s[i-1] == ‘(’:
record[i] = record[i-1]+2
if s[i] == ‘)’ and s[i-1] == ‘)’ and s[i-record[i-1]-1] == ‘(’:
record[i] = record[i-1]+record[i-record[i-1]-2]+2
代码如下:
class Solution {
public:
int longestValidParentheses(string s) {
vector<int> dp(s.size(), 0);
int res = 0;
for (int i = 1; i < s.size(); i++) {
if (s[i] == ')') {
if (s[i - 1] == '(')
dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;
else if (i - dp[i - 1] - 1 >= 0 && s[i - dp[i - 1] - 1] == '(')
dp[i] = (i - dp[i - 1] >= 2?dp[i - dp[i - 1] - 2]:0) + dp[i - 1] + 2;
res = max(res, dp[i]);
}
}
return res;
}
};
方案2
我们知道堆栈可以方便的判断一组输入是否合法;我们稍加变换就可以作为这道题的解法:
当遇到’('时压入其索引号
当遇到‘)’是吐出索引号,并记录当前索引号与吐出索引号后的堆栈栈顶之差(作为合法括号组合长度)
代码如下:
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> ss;
int res = 0;
ss.push(-1);
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') ss.push(i);
else {
ss.pop();
if (ss.empty()) ss.push(i);
else res = max(res, i - ss.top());
}
}
return res;
}
};
如有疑惑,强烈推荐阅读:here