您的位置:首页 > 理论基础 > 数据结构算法

2772. 数据结构实验之串一:KMP简单应用

2016-11-03 12:51 405 查看
数据结构实验之串一:KMP简单应用

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: