(最长回文字串)字符串中对称的子字符串的最大长度

输入一个字符串,输出该字符串中对称的子字符串的最大长度。比如输入字符串“goooogle”, 由于该字符串里最长的对称子字符串是“goooog”, 因此输出 6。

#include<iostream.h>
/*利用栈,字符进站,如果相同出战,不相同进站,对于奇数的情况加以判断
*/
void main()
{
	char *ch="aadgobabogleabcba";
	int i=0,maxlen=0,num=0,top=-1;
	char zh[50];

	while(ch[i]!='\0')
	{
		if(top==-1)
			zh[++top]=ch[i];
		else
		{
			if(zh[top]==ch[i])
			{
				num=num+2;
				top--;
			}
			else if(zh[top-1]==ch[i])//识别出奇数的情况
			{
				if(num%2==0)
				{
					top=top-2;
					num=3;
				}
				else
				{
					zh[++top]=ch[i];
					num=0;
				}
			}
			else
				zh[++top]=ch[i];


			if(num>maxlen)
				maxlen=num;
		}
		i++;
	}

	cout<<maxlen<<endl;
}
--------------------------------------------------------------------------------------------------------------------------

字符串中的每一个开始,向两边扩展,此时可分为两种情况:

(1)对称子串长度是奇数时, 以当前字符为对称轴向两边扩展比较

(2)对称子串长度是偶数时,以当前字符和它右边的字符为对称轴向两边扩展

#include<iostream.h>
/*字符串中的每一个开始,向两边扩展
*/
void main()
{
	char ch[]="aadgobabogleabcba";
	int num=0,maxlen=0;
	char *start,*left,*right;

	for(start=ch;*start;start++)
	{
		num=1;//对称字串可能为奇数时
		left=start-1;
		right=start+1;
		for(;left>=ch&&right<=ch+sizeof(ch)-2;left--,right++)
			if(*left==*right)
				num+=2;
			else
				break;
		if(num>maxlen)
			maxlen=num;


		num=0; //对称字串可能为偶数时
		left=start;
		right=start+1;
		for(;left>=ch&&right<=ch+sizeof(ch)-2;left--,right++)
			if(*left==*right)
				num+=2;
			else
				break;
		if(num>maxlen)
			maxlen=num;
	}

	cout<<maxlen<<endl;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值