posts - 183,  comments - 10,  trackbacks - 0

最长重复子串

问题描述
给定一个字符串,求出其最长重复子串
例如 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 ){
10     int i = 0;
11     while*&& (*p++ == *q++) )
12         ++i;
13     return i;
14 }
15 
16 int pstrcmp( const void *p1, const void *p2 ){
17     return strcmp( *(char* const *)p1, *(char* const*)p2 );
18 }
19 
20 int main(  ){
21     char ch;
22     int  n=0;
23     int  i, temp;
24     int  maxlen=0, maxi=0;
25     printf("Please input your string:\n");
26     while( (ch=getchar())!='\n' ){
27         a[n]=&c[n];
28         c[n++]=ch;
29     }
30     c[n]='\0';
31     qsort( a, n, sizeof(char*), pstrcmp );
32     for(i=0; i<n-1++i ){
33         temp=comlen( a[i], a[i+1] );
34         if( temp>maxlen ){
35             maxlen=temp;
36             maxi=i;
37         }
38     }
39     printf("%.*s\n",maxlen, a[maxi]);
40     system("PAUSE");
41     return 0;
42 }

 


参考:
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
posted on 2011-09-13 16:01 unixfy 阅读(7767) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理