```
public class Solution {
public int longestValidParentheses(String s) {
int[] dp = new int[s.length()+1];
int res = 0;
for (int i=1; i<s.length(); i++) {
if (s.charAt(i) == ')' && i-dp[i] >= 1 && s.charAt(i-dp[i]-1) == '(') {
dp[i+1] = dp[i-dp[i]-1] + dp[i] + 2;
res = Math.max(res, dp[i+1]);
}
}
return res;
}
}
```