您的位置:首页 > 编程语言 > C语言/C++

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

2014-12-07 16:06 330 查看
转载:请注明出处,/article/9411731.html,谢谢!

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

思路:借用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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: