```
public class Solution {
public int longestValidParentheses(String s) {
if (s.length() < 1) return 0;
char[] chars = s.toCharArray();
int p = 0;
int res = 0;
int[] stack = new int[chars.length + 1];
stack[0] = -1;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '(') stack[++p] = i;
else if (p == 0) stack[0] = i;
else res = Math.max(res, i - stack[--p]);
}
return res;
}
}
```