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.
方法一:stack和dp。Runtime: 21 ms beats 65.63% of java submissions.
public int longestValidParentheses(String s) {
int max = 0, start;
Stack<Integer> stack = new Stack();
if (!s.contains(")")) return 0;
int[] a = new int[s.length()];//a[i]记录longestValidParentheses(s.substring(0,i+1))
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == '(') stack.push(i);
else if (!stack.empty()) {
start = stack.pop();
a[i] = i - start + 1;
if (start > 1) a[i] += a[start - 1];
max = Math.max(max, a[i]);
}
}
return max;
}
方法二:当S[i] = ')'的时候,‘)’才会和前面的'('匹配。只有在当S[i] = ')'的时候,DP[i]才可能不为0,如果S[i] = '(',DP[i]没有被赋值,依然为初始化数据0。
下面代码中,比较难理解的是int j = i - 1 - DP[i - 1]; 如果DP[i - 1]=0,那么S[i-1]和其前面的字符没有进行匹配,此时 j = i - 1,看S[j]=S[i-1]是否为‘(’即可。
如果DP[i - 1]不等于0,那么S[i-1]和其前面的字符已经进行了匹配,结果是DP[i - 1],此时 j = i - 1- DP[i - 1],即 i - (S[i-1]和前面字符匹配的长度) -1 , S[i-1]所匹配的字符串的前一位,是否为‘(’即可。
Runtime: 16 ms beats 97.93% of java submissions.
public int longestValidParentheses(String s) {
char[] S = s.toCharArray();
int[] DP = new int[S.length];
int max = 0;
for(int i = 1; i < S.length; i++){
if(S[i] == ')'){
int j = i - 1 - DP[i - 1];
if(j >= 0 && S[j] == '('){
DP[i] = 2 + DP[i - 1] + (j > 0? DP[j - 1] : 0);
}
}
max = Math.max(max, DP[i]);
}
return max;
}