Password
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples input fixprefixsuffix output fix input abcdabc output Just a legend
题意:要求你找最长的相等前缀和后缀并且在字符串中间出现过(不是前缀和后缀)
解法:kmp的next数组的利用
这个题KMP的next数组的理解还是要有的,Next[i]表示在i之前,最长的公共前缀后缀的长度。所以说,我们首先要看看是否存在公共前缀后缀, 如果有,这只是保证了可能有解,因为我们还要看中间是否出现过。
首先我们用一个visit数组记录每一个位置的前缀长度是不是访问过(除了最后一个字符结尾的情况 因为找到中子串非后缀
最后我们利用next数组的性质,如果当前的匹配的长度在visit表中找不到,那么证明不存在非前缀与非后缀的子串符合条件,那么i=Next[i],也就是跳转到当前位置失配的重新匹配的位置(免去重复匹配的部分),也就是小于当前情况的最大的子串的后缀和前缀匹配的情况,然后再查visit表。知道找到答案为止,找不到答案证明不存在解。
#include <bits/stdc++.h>
#define ll long long
#define __max(a,b) a > b ? a : b
#define pii pair<int, int>
using namespace std;
const int maxn = 2e6 + 10;
string s;
int Next[maxn];//kmp中 pattern的next数组
bool vis[maxn];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> s;
int i = 1, j = 0;
int len = (int)s.length();
while(i < len)
{
if(s[i] == s[j])
{
Next[i] = j + 1;
i++; j++;
}
else
{
if(j == 0)
{
Next[i] = 0;
i++;
continue;
}
j = Next[j - 1];
}
}
for(int i = 0; i < len - 1; i++)
vis[Next[i]] = 1;
i = len - 1;
while(Next[i])
{
if(vis[Next[i]])
{
cout << s.substr(0, Next[i]) << endl;
exit(0);
}
i = Next[i] - 1;
}
cout << "Just a legend" << endl;
return 0;
}