对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?
,最长对称子串为s PAT&TAP s
,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include<stdio.h>
int main()
{
int i=0;
char str[1001];
int j,k;
int count = 0;
int max=0;
int sum=0;
int m;
int n;
while((str[i]=getchar())!='\n')
{
i++;
}
//特殊情况先讨论:当字符串长度就为1时
if(i==1)
{
printf("1");
return 0;
}
for(j=0;j<=i-1;j++)//外循环:从头开始
{
for(k=i-1;k>j;k--)//内循环:从尾开始
{
//每次循环重新定义两个变量n,m放一头一尾,把总数count清为0
m=k;
n=j;
count=0;
while(str[n]==str[m])//如果一头一尾相同
{
count+=2;//两者对称,对称子串数量加2
n+=1;//往后退一格
m-=1;//往前进一格
if(n==m||n-1==m) //n,m在中间相遇,循环结束,break退出
{
break;
}
}
if(n==m)//字符串总数为奇数时
{
count++;//对称子串数量在加1
sum=count;
}
else if(n-1==m)//字符串总数为偶数时
{
sum=count;
}
if(sum>max)
{
max=sum;
}
}
}
if(max==0)//最大数量为0,那么该字符数串数量就为1
{
printf("1");
return 0;
}
printf("%d",max);
return 0;
}