> For the complete documentation index, see [llms.txt](https://nataliekung.gitbook.io/solutions/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nataliekung.gitbook.io/solutions/longest_valid_parentheses.md).

# Longest Valid Parentheses

int longestValidParentheses(string s) {

vector\<int> f(s.size(),0);

int ret=0;

for(int i=s.size()-2;i>=0;i--){

int match = i+f\[i+1]+1;

if(s\[i]=='(' && match\<s.size() && s\[match]==')'){

f\[i]=f\[i+1]+2;

if(match+1\<s.size()) f\[i]+=f\[match+1];

}

ret=max(ret,f\[i]);

}

return ret;

}
