转载:请注明出处,http://blog.csdn.net/zonghongyan314/article/details/41787877,谢谢!
最近看了一个关于求字符串中最大对称子串的长度的比较有意思的算法,与大家分享一下!
思路:借用next数组防止回朔比较,例如:字符串str:"abcxxxxxcbvvvvv",它对应的next数组值:
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | |
str: | a | b | c | x | x | x | x | x | c | b | v | v | v | v | v |
next: | 1 | 1 | 1 | 1 | 2 | 3 | 4 | 5 | 7 | 9 | 1 | 2 | 3 | 4 | 5 |
#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;
}