I have seen a lot of good answers but it is not immediately clear how they are achieving the result. I am going to make an attempt to explain my solution using a stack. Every time we encounter '(' we push the index onto the stack and when we encounter ')' we pop the stack and use the current index minus the index at the top of the stack to be the current_length. we check against the max found so far and update if needed. Here is the code

```
public static int longestValidParentheses(String s) {
Stack<Integer> bracketStack = new Stack<Integer>();
int max_len=0;
int current_len=0;
int last = -1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
bracketStack.push(i);
}
else{
if(!bracketStack.isEmpty())
{
bracketStack.pop();
if(!bracketStack.isEmpty())
current_len = i-bracketStack.peek();
else
current_len=i-last;
max_len = Math.max(max_len,current_len);
}
else{
last = i;
}
}
}
return max_len;
}
```