/* 后缀数组实现查找最大子字符串 * 时间复杂度O(nlogn),时间花费 * 主要是在后缀数组的排序上面 * 使用qsort库函数排序,内部实现 * 应该是快排的改进算法 * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define NMAX 1024 char str[ NMAX ]; /* 存储字符串 */ char *pt[ NMAX ]; /* 存储顺序后缀数组 */ int cmp(const void *p1, const void *p2); int maxSubStr(const char *p1, const char *p2); int main(int argc, char **argv) { char ch; int n = 0, i; int maxi,tmp, maxlen = 0; char strtmp[ 128 ]; /* 存储最大子字符串 */ printf("please input a string to find the max substring:"); while ( (ch = getc(stdin)) != EOF ) { pt[ n ] = &str[ n ]; str[ n++ ] = ch; } str[ n ] = 0; /* 排序 */ qsort(pt, n, sizeof(char *), cmp); for ( i = 0; i < n; i++ ) { puts(pt[ i ]); } for ( i = 0; i < n-1; i++ ) { if ( (tmp = maxSubStr(pt[ i ], pt[ i + 1 ])) > maxlen ) { maxi = i; maxlen = tmp; } } strncpy(strtmp, pt[ maxi ], maxlen); strtmp[ maxlen ] = 0; puts(pt[ maxi ]); puts(strtmp); return 0; } int cmp(const void *p1, const void *p2) { return strcmp(*(char * const *)p1, *(char * const *)p2); } int maxSubStr(const char *p1, const char *p2) { int i = 0; while(*p1 && *p1++ == *p2++) i++; return i; }