您的位置:首页 > 其它

实现用后缀数组求字符串的最长重复字串

2013-07-22 21:09 295 查看
原理在博文后缀数组的应用已经说明,下面是实现代码

/*
问题描述
给定一个字符串,求出其最长重复子串
例如:abcdabcd
最长重复子串是 abcd,最长重复子串可以重叠
例如:abcdabcda,这时最长重复子串是 abcda,中间的 a 是被重叠的。
*/

#include <cstdio>
#include <cstring>
#include <iostream>
#include <cstdlib>
using namespace std;

int comlen(char *a, char *b)
{
int i=0;
while(*a && *a++==*b++) //返回a与b字符相同的长度
i++;
return i;
}

//用与回调函数
int pstrcmp(const void *a, const void *b)
{ return strcmp(*(const char* *)a, *(const char* *)b); }

int main(void)
{
int n=0, maxlen=0, maxi=0;
char a[1000],*pa[1000];
char ch;
while((ch=getchar())!='\n')
{
pa
=&a
;
a[n++]=ch;
}
a
='\0';
int i=0;
qsort(pa, n, sizeof(char*), pstrcmp); //得先排序后缀数组,不排序的话永远找不到
for(i=0; i<n-1; i++){
int temp=comlen(pa[i], pa[i+1]);
if(temp>maxlen) {
maxlen=temp;
maxi=i;
}
}
printf("the longest suffix is %s, and the length is %d\n", pa[maxi], maxlen);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐