后缀数组应用(最长重复子字符串)

给定一个输入字符串,查找其中最长的重复子字符串。例如“banana”的最长重复子字符串是“ana”。

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

#define MAXN 5000
char *buf[MAXN];

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

int comLen(const char *a, const char *b)
{
	if (NULL == a || NULL == b)
	{
		return -1;
	}

	int result = 0;
	while ((*a != '\0') && (*b != '\0')) 
	{
		if (*a == *b)
		{
			result++;
		}
		else
		{
			break;
		}
		a++;
		b++;
	}

	return result;
}

int maxComLen(char *a, int n)
{
	for (int i = 0; i < n; i++)
	{
		buf[i] = &a[i];
	}
    
	qsort(buf, n, sizeof(char*), pstrcmp);

	int result = 0;
	int pos = 0;
	for (int i = 0; i < n-1; i++)
	{
		int len = comLen(buf[i], buf[i+1]);
        if (len > result)
		{
			result = len;
			pos = i;
		}
	}
    for (int i = 0; i < result; i++)
	{
	    cout << buf[pos][i];
	}
	cout << endl;

	return result;
}

int main()
{
	char a[] = "Ask not what your country can do for you, but what you can do for your country";
    cout << maxComLen(a, strlen(a)) << endl;

	return 0;
}

       


你可能感兴趣的:(后缀数组应用(最长重复子字符串))