字符串中最大对称子串的长度(C++软件工程师面试题)

转载:请注明出处,http://blog.csdn.net/zonghongyan314/article/details/41787877,谢谢!

最近看了一个关于求字符串中最大对称子串的长度的比较有意思的算法,与大家分享一下!

思路:借用next数组防止回朔比较,例如:字符串str:"abcxxxxxcbvvvvv",它对应的next数组值:

 01234567891011121314
str:abcxxxxxcbvvvvv
next:111123457912345

将“死磕类”的算法时间复杂度提高到O(n)。与KMP的next异曲同工O(∩_∩)O~, 只可惜至今没有理解KMP!


#include<iostream>
using namespace std;
/****************************************************
*******@Author仁子欣****2014年12月7号****************
功能:输入一个字符串,输出该字符串中最大对称子串的长度
例如:"abacc"返回3,"a"返回1,abb返回4;
输入:字符串str
返回:int最大对称子串的长度
*****************************************************/
int StrSymmetricCounts(const char* str);

int main()
{
    char* str="abcxxxxxxxxccccc";
	printf("源字符串为:%s\n",str);
	int len = StrSymmetricCounts(str);
	printf("最大对称子串长度:%d\n",len);
	return 0;
}


int StrSymmetricCounts(const char* str)
{
	if(str==NULL)return-1;
	int len=strlen(str);
	int maxlen=1;
	int next[30];//next数组类似KMP中的next数组
	             
	next[0]=1;
	int i=1;
	while(i<len)
	{
		int max=1;
		if((i-next[i-1]-1)>=0 && str[i]==str[i-next[i-1]-1])
		{//通过next数组回退比较
			max = max > (next[i-1]+2) ? max: (next[i-1]+2);
		}
		int k=1;
		while(str[i]==str[i-k])//如果字符串的数组相邻的相等
			k++;
		max = max > k?max: k;

		next[i]=max;//将next数组进行赋值
		cout<<"next["<<i<<"]="<<next[i]<<"; "<<endl;

		if(next[i]>maxlen)
		{
			maxlen=next[i];	   
		}
                i++;
	}
	return maxlen;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值