对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?,最长对称子串为s PAT&TAP s,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
之前仅仅样例过了,最短串没有考虑,偶数对称也没有考虑,奇数对称也有错误,全对称是错的,然后改为 j<=n/2(之前未加等号),而且之前 if(max<l) max=l; 是放在else里的,不知道为什么不对,反正感觉不太对劲,放外面就对了,
有一点需要注意,string类的size()和length()的返回值是无符号数,-1会出问题,然后就定义了个int n 以防万一,之前就因为这个隐蔽的问题debug了好久
#include <bits/stdc++.h>
#define pb push_back
#define mem(a,b) memset(a,b,szieof a)
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
int main()
{
// freopen("D:\\LYJ.txt","r",stdin);
string s;
getline(cin,s);
int n=s.length(),max=0,l;
if(n>=1) max=1;
for(int i=1;i<n-1;i++)//奇数对称
{
l=1;
for(int j=1;j<=n/2;j++)
{
if((i+j)>=n||(i-j)<0) break;
if(s[i+j]==s[i-j]) l+=2;
else break;
if(max<l) max=l;
// cout<<"i:"<<i<<"j:"<<j<<" "<<max<<" "<<l<<endl;
}
}
for(int i=0;i<n-1;i++)//偶数对称
{
l=0;
for(int j=0;j<=n/2;j++)
{
if((i-j)<0||(i+1+j)>=n) break;
if(s[i-j]==s[i+1+j]) l+=2;
else break;
if(max<l) max=l;
}
}
cout<<max;
return 0;
}