next数组用于判断又是S的前缀又是S的后缀,所以剩下的需要解决:
1.找到S的各种前缀和后缀,从最长的向最短的考虑
例如:
a b c a b c a b c
next数组: -1 0 0 0 1 2 3 4 5 6
那么最长的前后缀长度为6,第二长的是next[6]=3,第三长的是next[3]...
2.在一种前缀和后缀的情况下,看中间是否有相同的字符串,运用到strstr函数,strstr(a,b)判断字符串a是否含有字符串b。
血的教训:
1.strlen用多了会疯狂超时!!!
2.strncpy(a,b+2,10)----将b字符串的第三个字符开始取10个字符赋值给a
每次循环赋值后需要填写 a[10]=‘\0’;
#include<bits/stdc++.h>
using namespace std;
int next_[1000010];
char s[1000010]; //原串
char t[1000010];//目标串
char s_temp[1000010];//s的临时串--去头去尾
void find_next(int len){//求s的next数组
int i=0,j=-1;
next_[0]=-1;
while(i<=len){
if(j==-1||s[i]==s[j]){
i++;
j++;
next_[i]=j;
}
else{
j=next_[j];
}
}
}
int main( )
{
cin>>s;
int len=strlen(s);
find_next(len);
if(next_[len]==0){
cout<<"Just a legend";
return 0;
}
int temp=next_[len];
strcpy(s_temp,s+1);
s_temp[strlen(s_temp)-1]='\0';
while(temp!=0){
//cout<<"temp:"<<temp<<endl;
strncpy(t,s,temp);
t[temp]='\0';
//cout<<t<<endl;
//cout<<s_temp<<endl;
if(strstr(s_temp,t)){
cout<<t;
return 0;
}
temp=next_[temp];
}
cout<<"Just a legend";
return 0;
}