【PTA】最长对称子串

7-64 最长对称子串(25 分)

对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?,最长对称子串为s PAT&TAP s,于是你应该输出11。

输入格式:

输入在一行中给出长度不超过1000的非空字符串。

输出格式:

在一行中输出最长对称子串的长度。

输入样例:

Is PAT&TAP symmetric?

输出样例:

11

思路:

自己写的代码只有17分,有几个测试点过不了,去网上找了网友的思路。

大致分为两种情况:

对称子串是奇数时,起始的ans为1,以中间的字符为对称轴,向两边不断扩展,每次ans+2;

对称子串是偶数时,起始的ans为0,以中间的两个字符为对称抽,向两边扩展

代码:

#include <stdio.h>
#include <string.h>
const int num=1001;
int main(int argc,const char *argv[])
{
	char s[num];
	fgets(s,num,stdin);
	int len=strlen(s);
	int max=1,ans=0;
	int x,y;
	for(int i=0;i<len-1;i++)//对称字串为奇数
	{
		int ans=1;
		x=i-1;
		y=i+1;
		while(s[x]==s[y]&&x>=0&&y<len)
		{
			x--;
			y++;
			ans+=2;
		}
		if(ans>max)
		{
			max=ans;
		}
	}
	for(int j=0;j<len-1;j++)//对称字串为偶数
	{
		ans=0;
		x=j;
		y=j+1;
		while(s[x]==s[y]&&x>=0&&y<len)
		{
			x--;
			y++;
			ans+=2;
		}
		if(ans>max)
		{
			max=ans;
		}
	}
	printf("%d",max);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/jiangxiaoshan123/article/details/81904563