题目链接
题目大意
给出一个字符串,让你判断是否存在一个字符串的同时出现在字符串开头,中间(不能从第一个字母开始或者以最后一个字母结尾),和最后。若存在求其最长
题目思路
hash:看到第一眼觉得是Kmp,但自己基本不怎么知道kmp,想用hash水一下,先写了一下hash+二分,但后面发现其实他并不满足二分的条件。举个例子,假如说你判断前缀为4的时候,答案是不存在的,但这并不能说明前缀为5或者3的时候是不存在的。那么就直接暴力二分,居然过了o(n^2),应该数据有点水
kmp:待补
hash
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef unsigned long long ull;
const int maxn=1e6+5;
char s[maxn];
ull pre[maxn],base[maxn];
int d,flag=1;
bool check(int x){
ull hash1=pre[x],hash2=pre[d]-pre[d-x]*base[x];
if(hash1!=hash2){
return 0;
}
for(int i=2;i+x-1<=d-1;i++){//只要不包括第一个和最后一个元素即可
ull hash3=pre[i+x-1]-pre[i-1]*base[x];
if(hash1==hash3){
return 1;
}
}
return 0;
}
int main(){
scanf("%s",s+1);
d=strlen(s+1);
base[0]=1;
for(int i=1;i<=d;i++){//hash 进制29
pre[i]=pre[i-1]*29+s[i]-'a'+1;
base[i]=base[i-1]*29;
}
int ans=-1;
for(int i=d;i>=1;i--){//枚举长度
if(check(i)){
ans=i;
break;
}
}
if(ans==-1){
printf("Just a legend\n");
}else{
for(int i=1;i<=ans;i++){
printf("%c",s[i]);
}
printf("\n");
}
return 0;
}