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"()()"
思路:
dp好题, if(s[i] == "(") 就不用管了, ==")", 好戏来了, 如果s[i-1]="(", 就简单的相加2, dp[i]= dp[i-2]+2, 如果s[i-1]=")" and s[i-dp[i-1]-1] == "(", dp[i] = dp[i-1]+2+dp[i-dp[i-1]-2], 就是找之前的最长。就是组合。
class Solution {
public int longestValidParentheses(String s) {
if(s.length()<=0)return 0;
int res = 0;
int []dp = new int[s.length()+1];
for(int i=1;i<s.length();i++){
if(s.charAt(i) == ')' ){
if(s.charAt(i-1)== '('){
dp[i] = (i-2) >=0 ? dp[i-2]+2:2;
res = Math.max(res,dp[i]);
}else{
if(i-dp[i-1]-1 >= 0 && s.charAt(i-dp[i-1]-1 ) == '('){
dp[i] = dp[i-1]+2+((i-dp[i-1]-2) >= 0 ? dp[i-dp[i-1]-2] : 0);
res = Math.max(res,dp[i]);
}
}
}
}
return res;
}
}