您的位置:首页 > 其它

最长重复子串

2013-04-12 23:11 106 查看
问题描述
给定一个字符串,求出其最长重复子串
例如 abcdabcd
最长重复子串是 abcd
最长重复子串可以重叠
例如
abcdabcda
这时最长重复子串是 abcda
中间的 a 是被重叠的。

直观的解法是,首先检测长度为 n - 1 的字符串情况,如果不存在重复则检测 n - 2, 一直递减下去,直到 1 。
这种方法的时间复杂度是 O(N * N * N),其中包括三部分,长度纬度、根据长度检测的字符串数目、字符串检测。

改进的方法是利用后缀数组
后缀数组是一种数据结构,对一个字符串生成相应的后缀数组后,然后再排序,排完序依次检测相邻的两个字符串的开头公共部分。
这样的时间复杂度为:
生成后缀数组 O(N)
排序 O(NlogN*N) 最后面的 N 是因为字符串比较也是 O(N)
依次检测相邻的两个字符串 O(N * N)
总的时间复杂度是 O(N^2*logN), 由于第一种方法的 O(N^3)

后缀数组的实现:
代码摘自 CSDN 论坛
http://topic.csdn.net/u/20071002/22/896b1597-fc39-466e-85d3-5bef6f7442f6.html

1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 #define MAXCHAR 5000 //最长处理5000个字符
6
7 char c[MAXCHAR], *a[MAXCHAR];
8
9 int comlen( char *p, char *q ){
int i = 0;
while( *p && (*p++ == *q++) )
++i;
return i;
}

int pstrcmp( const void *p1, const void *p2 ){
return strcmp( *(char* const *)p1, *(char* const*)p2 );
}

int main( ){
char ch;
int n=0;
int i, temp;
int maxlen=0, maxi=0;
printf("Please input your string:\n");
while( (ch=getchar())!='\n' ){
a
=&c
;
c[n++]=ch;
}
c
='\0';
qsort( a, n, sizeof(char*), pstrcmp );
for(i=0; i<n-1; ++i ){
temp=comlen( a[i], a[i+1] );
if( temp>maxlen ){
maxlen=temp;
maxi=i;
}
}
printf("%.*s\n",maxlen, a[maxi]);
system("PAUSE");
return 0;
}

参考:
http://topic.csdn.net/u/20071002/22/896b1597-fc39-466e-85d3-5bef6f7442f6.html
http://blog.csdn.net/kongming_acm/article/details/6232439
http://blog.sina.com.cn/s/blog_5133d4dd0100a4qd.html
http://www.programbbs.com/bbs/view35-20014-1.htm
http://hi.baidu.com/fangm/blog/item/58fd1a4c20a5eafdd72afcd0.html
http://www.cnblogs.com/dyh333/articles/1801714.html
http://www.byvoid.com/blog/tag/%E6%9C%80%E9%95%BF%E9%87%8D%E5%A4%8D%E5%AD%90%E4%B8%B2/
http://www.cppblog.com/Joe/archive/2011/08/19/153851.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: