问题 D: DS串应用—最长重复子串
时间限制: 1 Sec 内存限制: 128 MB
题目描述
求串的最长重复子串长度(子串不重叠)。例如:abcaefabcabc的最长重复子串是串abca,长度为4。
输入
测试次数t
t个测试串
输出
对每个测试串,输出最长重复子串长度,若没有重复子串,输出-1.
样例输入
3
abcaefabcabc
szu0123szu
szuabcefg
样例输出
4
3
-1
#include<iostream>
#include<string>
#include<math.h>
using namespace std;
int matched_maxstr(string str)
{
if (str.length() == 1)return -1;
string substr,ans="-1";
int j =str.length()-1;
int maxlen = str.length() / 2;
while (maxlen>0)
{
for (int i=0; i < str.size()-maxlen; i++)
{
substr = str.substr(i, maxlen);
ans = str.substr(i + maxlen);
if (ans.find(substr) != string::npos)
{
return maxlen;
}
}
maxlen--;
}
return -1;
}
int main()
{
int t;
cin >> t;
while (t--)
{
string str;
cin >> str;
int ans;
ans = matched_maxstr(str);
cout << ans << endl;
}
return 0;
}