Description
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 stringS, Carved on a rock below the temple's gates. asterix supposed that's the password that opens the temple and read the string aloud. however, nothing happened. then Asterix supposed that a password is some substringTOf the stringS.
Prefix supposed that the substringTIs the beginning of the stringS; Suffix supposed that the substringTShocould be the end of the stringS; And Obelix supposed thatTShocould be located somewhere inside the stringS, That is,TIs neither its beginning, nor its end.
Asterix chose the substringTSo 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 substringTAloud, the temple doors opened.
You know the stringS. Find the substringTOr determine that such substring does not exist and all that's been written abve is just a nice legend.
Input
You are given the stringSWhose length can vary from1 to 106 (random), consisting of small Latin letters.
Output
Print the stringT. If a suitableTString does not exist, then print "just a legend" without the quotes.
Sample Input
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend
Question: Find the substring that appears in the middle and the end.
Idea: KMP is to pay attention to the situation of abcdabcdabcd, So I = f [I];
You can understand the code by yourself.
AC code:
#include <cstdio>#include <iostream>#include <algorithm>#include <cmath>#include <cstring>#include <stdlib.h>using namespace std;int f[1000006];char s[1000006];int len;int vis[1000006];void init(char s[]){ f[0]=0;f[1]=0; for(int i=1;i<len;i++){ int j=f[i]; while(j&&s[j]!=s[i]) j=f[j]; f[i+1]=(s[i] == s[j] ? j+1 : 0); }}int main(){ scanf("%s",&s); len=strlen(s); init(s); memset(vis,false,sizeof(vis)); for(int i=0;i<len;i++){ vis[f[i]]=true; } int i=len,j=0; bool flag=false; while(f[i]!=0){ if(vis[f[i]]){ for(int j=0;j<f[i];j++){ printf("%c",s[j]); } flag=true; break; } i=f[i]; } if(!flag){ printf("Just a legend"); } printf("\n"); return 0;}
Zookeeper