题目:
从一个字符串里面找到存在前缀和后缀并且在字符串里面出现过的子串。
题解:
先求next数组,再用kmp配对。
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 1;
int Next[N];
void getNext(string s)
{
int n = s.length();
Next[0] = -1;
int k = -1, j = 0;
while (j < n)
{
if (k == -1 || s[j] == s[k])
{
j++; k++;
Next[j] = k;
}
else
{
k = Next[k];
}
}
}
bool kmp(string s, string p)
{
int i = 0, j = 0;
int m = s.length(), n = p.length();
while (i < m && j < n)
{
if (j == -1 || s[i] == p[j]) i++, j++;
else j = Next[j];
}
if (j == n) return true;
return false;
}
int main()
{
ios::sync_with_stdio(0);
string a;
cin >> a;
int n = a.length();
getNext(a);
int x = Next[n ];
bool flag = false;
while (x)
{
if (kmp(a.substr(1, n - 2), a.substr(0, x)))
{
cout << a.substr(0, x) << endl;
flag = true;
break;
}
x = Next[x];
}
if (!flag) cout << "Just a legend" << endl;
return 0;
}