L2-008 最长对称子串
分数 25
对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?
,最长对称子串为s PAT&TAP s
,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
题解
暴力循环找到所有子串,如果子串长度小于当前最长则跳过,否则就判断是否是对称的。
#include<bits/stdc++.h>
using namespace std;
string s;
int maxn=1;
bool judge(string t)
{
for(int i=0;i<t.size()/2;i++)
{
if(t[i]!=t[t.size()-i-1])
{
return false;
}
}
return true;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
getline(cin,s);
for(int i=0;i<s.size();i++)
{
for(int j=i+1;j<s.size();j++)
{
string t=s.substr(i,j-i+1);//截取子串
if(maxn>=t.size())
{
continue;
}
else
{
if(judge(t))
{
maxn=t.size();
}
}
}
}
cout<<maxn<<endl;
return 0;
}