1. 程式人生 > >找出字串的最長重複子串

找出字串的最長重複子串

一個長度為10000的字串,寫一個演算法,找出最長的重複子串,如abczzacbca,結果是bc。

提示:此題是字尾樹/陣列的典型應用,即是求字尾陣列的height[]的最大值。

#include <stdio.h>
#include <stdlib.h>
#define SIZE 5000

char str[SIZE], *pstr[SIZE];

int cmpLen(char* p, char* q) {
	int len = 0;
	while (*p && *(p++) == *(q++)) {
		len++;
	}
	return len;
}

int pstrcmp(char* p, char* q) {
	return strcmp(*(char* const *) p, *(char* const *) q);
}

//初始化尾序陣列
void initRearArray(char* src) {
	int i = 0;
	while (*(src + i)) {
		pstr[i] = &str[i];
		str[i] = *(src + i);
		i++;
	}
	str[i] = '\0';
}

//找出最大重複子串
char* findMaxRepeatStr() {
	int len = strlen(str);
	int j = 0;
	int maxLen = 0, maxId = 0;
	int temp = 0;
	for (j = 0; j < len - 1; ++j) {

		if ((temp = cmpLen(pstr[j], pstr[j + 1])) > maxLen) {
			maxId = j;
			maxLen = temp;
		}
	}

	//擷取子串
	char* result = calloc(sizeof(char), maxLen + 1);
	char* selectedStr = pstr[maxId];
	for (j = 0; j < maxLen; j++) {
		result[j] = *(selectedStr + j);
	}
	result[j] = '\0';
	return result;
}

int main(void) {
	char* src = "abcazzacbczacbc";

	initRearArray(src);

	//按字典序對字串指標陣列快排
	qsort(pstr, strlen(str), sizeof(char*), pstrcmp);

	printf("最大重複子串:");
	puts(findMaxRepeatStr());

	return EXIT_SUCCESS;
}