PTA 7-17 最长对称子串

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

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

输入格式:

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

输出格式:

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

输入样例:

Is PAT&TAP symmetric?

输出样例:

11
#include<bits/stdc++.h>
using namespace std;
char s[1001];
int main()
{
	gets(s);
	int len=strlen(s);
	int max =1,ans=0;
	int x,y,i,j;
	for( i=0;i<len-1;i++)
	{
		ans=0;
		x=i;
		y=i+1;
		for(;x>=0&&y<len;x--,y++)
		{
			if(s[x]!=s[y]&&(x>=0&&y<len))break;
			else if(s[x]==s[y]&&(x>=0&&y<len))
			{
				ans+=2;
			} 			
		}
	if(ans>max)
		max=ans;
	}
	for( i=1;i<len-1;i++)
	{
		ans=1;
		x=i-1;
		y=i+1;
		
		for(;(x>=0&&y<len);x--,y++)
		{
			if(s[x]!=s[y]&&(x>=0&&y<len))break;
			else if(s[x]==s[y]&&(x>=0&&y<len))
			{
				ans+=2;
			} 
		}
			if(ans>max)
		max=ans;
	}
	cout<<max<<endl; 
 	return 0;
}

猜你喜欢

转载自blog.csdn.net/GAIYA2050/article/details/81152026
今日推荐