7-12 最长对称子串 (25 分)(思维)

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

输入格式:

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

输出格式:

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

输入样例:

Is PAT&TAP symmetric?

输出样例:

11

思路:对一个字符串我们从中间向两边扩展并判断是否对称

  分两种情况:

  如果对称子串len是奇数 ,以该字符串为轴向两边扩展

  如果对称子串len是偶数,那么就以两个字符为轴向两边扩展

代码: 

#include<iostream>
using namespace std;
int main()
{
	string s;
	getline(cin,s);
	int maxx=1,ans;
	int x,y;
	int len=s.length();
	for(int i=0;i<len;i++)
	{
		ans=0;
	    x=i;
	    y=i+1;
	    while(s[x]==s[y]&&x>=0&&y<len)
	    {
	    	x--;
	    	y++;
	    	ans+=2;
		}
		maxx=max(maxx,ans);
	} 
	for(int i=1;i<len;i++)
	{
		ans=1;
		x=i-1;
		y=i+1;
		while(s[x]==s[y]&&x>=0&&y<len)
	    {
	    	x--;
	    	y++;
	    	ans+=2;
		}
		maxx=max(maxx,ans);
	}
	cout<<maxx<<endl; 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/daoshen1314/article/details/88316745