/*此题不像传统意义上的串匹配,此题只要一个串模式串是需要根据题目条件在母串中找的,很好的题在kmp理解上加深对该算法的理解,再次注意next的重要性且next数组只和模式穿有关,next数组是存放当前最长匹配长度串的,因此相同next数组中的值表示的串是相同的,详解见代码很好的题*/
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char ch[1000005];
int next[1000005];
int hash[1000005];
void getnext()
{
int len=strlen(ch);
int i=0,j=-1;
next[0]=-1;
while(i<len)
{
if(j==-1 || ch[i]==ch[j])
{
i++;
j++;
next[i]=j;
//cout << "next[" << i << "]" << " "<<next[i]<<endl; //不懂主函数中while循环 就可以打印出来看看有助于直观理解
hash[j]++; //hash表统计长度为j的子串数目,因为在kmp串匹配中长度相同的串所表示的串是相同的
}
else
j=next[j];
}
}
int main()
{
while(cin>>ch)
{
int len=strlen(ch);
memset(hash,0,sizeof(hash));
getnext();
int i=len;
int flag=0;
hash[next[len]]--;
while(next[i]) //通过回溯的方法判断整个模式串
{
if(hash[next[i]]) //查找向前回溯后的next是否存在一个长度
{
flag=1;
break;
}
else
{
next[i]=next[next[i]];
}
}
if(!flag)
cout<<"Just a legend"<<endl;
else
{
for(int j=0;j<next[i];j++)
cout<<ch[j];
cout<<endl;
}
}
return 0;
}
codeforces 126B kmp串匹配问题
最新推荐文章于 2021-08-26 22:05:42 发布