// --------------------------------------
// 求串S中出現的第一個最長重複字串及其位置
// ---------------------------------------ios
#include <iostream>
#include <string>
using namespace std;算法
// KMP算法中,next數組所存的是,在第j個字符前存在一個長度爲next[j]-1的重複子串
// 重複子串:SubString(S,i,len) = SubString(S,j,len)數組
void GetNext(string s, int next[], int length) {
int i = 0;
int j = -1;
next[0] = -1;
while (i < length) {
if (j == -1 || s[i] == s[j]) {
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}spa
int MaxNext(int a[], int length) {
int max = -1;
for (int i = 0; i < length; i++) {
max = max < a[i] ? a[i] : max;
}
return max;
}string
int MaxRepSubString(string s,int &l) {
l = 0;
int pos = -1,i;
int max = -1;
int length = s.length();
for (i = 0; i < length - 1; i++) {
string tmp(s, i, length - i);
int *next = new int[tmp.length()];
GetNext(tmp, next, tmp.length());
max = MaxNext(next, tmp.length());
if (tmp[tmp.length() - 1] == tmp[max]) {
max = max + 1;
}
if (l < max) {
l = max;
pos = i;
}
}
return pos;
}io
int main() {
string s = "abaabaa";
int l;
int pos = MaxRepSubString(s,l);
if (pos == -1)
cout << "不存在" << endl;
else
{
string res(s, pos, l);
cout << res << endl;
}stream
system("pause");
return 0;
}next