题目描述
求串的最长重复子串长度(子串不重叠)。例如:abcaefabcabc的最长重复子串是串abca,长度为4。
输入
测试次数t
t个测试串
输出
对每个测试串,输出最长重复子串长度,若没有重复子串,输出-1.
样例输入
3
abcaefabcabc
szu0123szu
szuabcefg
样例输出
4
3
-1
思路:
实现代码:
#include<iostream>
#include<string>
using namespace std;
void GetNext(string p, int next[])
{
next[0] = -1;
int i, j;
i = 0;
j = -1;
while (i<p.length())
{
if (j == -1 || p[i] == p[j])
{
++i;
++j;
next[i] = j;
}
else
j = next[j];
}
}
int main()
{
int n;
cin >> n;
string s;
string re;
int i, j = -1,k;
int max = 0;
while (n--)
{
int next[100] = { 0 };
max = -1;
cin >> s;
re=s;
for (i = 0, k = s.length() - 1; k >= 0; i++, k--)
{
re[i] = s[k];
}
GetNext(s, next);
for (i = 0; i <= s.length(); ++i)
{
if (next[i]>max && next[i]<=s.length()/2)
max = next[i];
}
GetNext(re, next);
for (i = 0; i <= re.length(); ++i)
{
if (next[i]>max && next[i]<=re.length()/2)
max = next[i];
}
if (max == 0)
cout << j << endl;
else
{
cout << max << endl;
}
}
return 0;
}