126B Password [Extended kmp learning]

Subject to the effect

Give you a string, it is seeking a substring substring makes this even if the prefix is ​​not a prefix and suffix where suffix is ​​not reappeared

analysis

Extension is defined kmp z [i] i ~ n denotes the length of the substring and the entire string is the longest common prefix z [i]

So the problem is to find a position such that z [i] = n-i + 1

This ensures a prefix and suffix

Then if there is a z [j] is determined before re = z [i]

Any representative of the length of the string also appeared in the middle

This can be directly output

Code

 void get_z(){
    int i,j,k,l=0,r=0;
    for(i=1;i<n;i++){
      if(i<=r)z[i]=min(r-i+1,z[i-l]);
      while(i+z[i]<n&&s[z[i]]==s[i+z[i]])z[i]++;
      if(i+z[i]-1>r)r=i+z[i]-1,l=i;
    }
}
int main(){
    int i,j,k;
    scanf("%s",s);
    n=strlen(s);
    get_z();
    for(i=1;i<n;i++){
      if(z[i]==n-i&&mx>=n-i){
          for(j=0;j<z[i];j++)cout<<s[j];
          puts("");
          return 0;
      }
      mx=max(mx,z[i]);
    }
    puts("Just a legend");
    return 0;
}

Guess you like

Origin www.cnblogs.com/yzxverygood/p/11441357.html