```
class Solution {
public:
int longestValidParentheses(string s) {
int len=0;
stack<int> idx;
idx.push(-1);
for (int i=0; i<s.size(); ++i) {
if (s[i]=='(') {
idx.push(i);
} else {
idx.pop();
if (idx.empty()) {idx.push(i); continue;}
len=max(len, i-idx.top());
}
}
return len;
}
};
```