題目描述
求串的最長重復子串長度(子串不重疊),例如: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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/221071.html
標籤:其他
下一篇:資料結構--線段樹
