#include<iostream>
#include<cstring>
using namespace std;
char s1[1000005],s2[1000005];
int next[1000005],k=0;
void get_next()
{
int i=0,j=-1;
next[0]=-1;
while(s2[i]!='\0')
{
if(j==-1||s2[i]==s2[j])
{
i++;j++;
//if(s[i]!=s[j])
next[i]=j;
// else next[i]=next[j];
}
else j=next[j];
}
}
int KMP()
{
int i=0,j=0;
get_next();
int len1=strlen(s1);
int len2=strlen(s2);
while(i<len1&&j<len2)
{
if(j==-1||s1[i]==s2[j])
{
++i;++j;
}
else j=next[j]; //i不变,j后退
}
if(j>=len2)
cout<<i-len2+1<<endl;
else cout<<"-1"<<endl;
}
int main()
{
while(cin>>s1>>s2)
{
KMP();
}
return 0;
}
2772. 数据结构实验之串一:KMP简单应用
最新推荐文章于 2020-11-23 20:04:15 发布