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

本文介绍了一种查找给定字符串中最长重复子字符串的方法,并提供了一个C++实现示例。该方法通过比较字符串的不同部分来找出最长的重复序列。

给定一个输入字符串,查找其中最长的重复子字符串。例如“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;
}

       


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值