```
public class Solution {
public int longestValidParentheses(String s) {
if (s == null || s.length() <= 1) return 0;
int ml = 0;
int[] good = new int[s.length()];
for (int i = 1; i < s.length(); ++i) {
if (s.charAt(i) == ')') {
int j = i-1;
boolean matched = false;
while (j >= 0) {
if (s.charAt(j) == '(') {
if (matched) break;
matched = true;
--j;
}
else {
if (good[j] == 0) break;
j -= good[j];
}
}
if (matched) {
good[i] = i - j;
ml = Math.max(ml, good[i]);
}
}
}
return ml;
}
}
```