#include<string.h>// @lc code=start
intlongestValidParentheses(char*s){unsignedshortlength=strlen(s);// 动态规划 is too much memory cost
// cutoff left right bound
while(length>0&&s[0]!='('){s++;length--;}while(length>0&&s[length-1]!=')'){length--;}s[length]=0;if(length<=2)returnlength==2?2:0;intret=0;unsignedshortlnum=1,rnum=0,delta=0;for(inti=1;i<length;i++){if(s[i]=='(')lnum+=1;elsernum+=1;if(rnum>lnum){if(lnum<<1>ret)ret=lnum<<1;lnum=0;rnum=0;delta=i+1;}}if(lnum==rnum)returnrnum<<1<ret?ret:rnum<<1;if(rnum<<1<=ret)returnret;s=s+delta;length-=delta;lnum=0,rnum=1;for(inti=length-2;i>=0;i--){if(s[i]==')')rnum+=1;elselnum+=1;if(lnum>rnum){if(rnum<<1>ret)ret=rnum<<1;lnum=0;rnum=0;}}returnlnum<<1<ret?ret:lnum<<1;}