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.
主题思想: 关于这种匹配的,一般用栈结构,所以第一种解法是利用栈结构,这道题某种意思上和求最长连续子序列有点像,因为是求最大子字符串长度,所以只要记录合法的字串其实位置就可以了。
思路: 遇见合法的对,就出栈,并计算更新最大长度,
其他情况入栈,
具体代码:
public class Solution {
public int longestValidParentheses(String s) {
int max = 0;
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == ')' && !stack.empty() && s.charAt(stack.peek())== '(')
{
stack.pop();
if(stack.empty()) max=Math.max(max,i+1);
else max=Math.max(max,i-stack.peek());
}
else{
stack.push(i);
}
}
return max;
}
}
第二种解法 动态规划: 这道题也是一道动态规划题,
所以脑子里应该有意思到这是一道dp题,
状态转移方程,
如果遇见合法对
dp[i]=2+dp[i-1];
然后判断 i-dp[i] 是否下标合法,如果合法
dp[i]=dp[i]+dp[i-dp[i]];
具体代码:
public class Solution {
public int longestValidParentheses(String s) {
int mx=0;
if(s==null||s.length()<2) return 0;
int n=s.length();
int [] dp=new int[n];
for(int i=0;i<n;i++) dp[i]=0;
int open=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='(') open++;
else if(s.charAt(i)==')'&&open>0){
dp[i]=2+dp[i-1];
if(i-dp[i]>0) dp[i]+=dp[i-dp[i]];
open--;
}
if(dp[i]>mx) mx=dp[i];
}
return mx;
}
}