Longest Valid Parentheses
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) {
char[] S = s.toCharArray();
int[] V = new int[S.length];
int open = 0;
int max = 0;
for (int i = 0; i < S.length; i++) {
if (S[i] == '(')
open++;
if (S[i] == ')' && open > 0) {
V[i] = 2 + V[i - 1];
if(i-V[i] >= 0) {
V[i] += V[i-V[i]]; //处理“()()”这种情况
}
open--;
}
if (V[i] > max)
max = V[i];
}
return max;
}
}