描述
示例1
输入:
"(()"
返回值:
2
示例2
输入:
"(())"
返回值:
4
Code(时间为解决)
bool isValid(string s)
{
if(s.length()%2)
return false;
string temp=s;
int pos;
for(int i=0;i<s.length();)
{
if((pos=temp.find("()"))!=string::npos)
{
temp=temp.erase(pos,2);
}
else
{
break;
}
}
return temp.length()==0;
}
int longestValidParentheses(string s) {
if(s.find("()")==string::npos)
return 0;
int maxlen=0;
for(int i=0;i<s.length();i++)
{
for(int j=1;j<=s.length()-i;j++)
{
string temp=s.substr(i,j);
// cout<<temp<<"-----"<<endl;
if(isValid(temp))
{
// cout<<temp<<endl;
maxlen=max(maxlen,(int)temp.length());
}
}
}
cout<<"max="<<maxlen<<endl;
return maxlen;
}