求不重叠的模式串有多少个。
#include<stdio.h>
#include<string>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
#define maxn 1000006
int f[10005];
char s1[maxn],s2[maxn];
int cnt;
void net(int n)
{
// int n=strlen(s2);
int j=0;
f[0]=0;
f[1]=0;
// cout<<"fuck"<<endl;
for(int i=2;i<n;i++)
{
j=f[i-1];
while(j&&s2[i-1]!=s2[j])
j=f[j];
// cout<<"fuck"<<endl;
if(s2[i-1]==s2[j])
f[i]=j+1;
else
f[i]=0;
}
}
int kmp(int n,int m)
{
int n1=n;
int n2=m;
int j=0;
int i=0;
for(i=0;i<n1;i++)
{
while(j&&s1[i]!=s2[j])
j=f[j];
if(s1[i]==s2[j])
j++;
if(j==n2)
{
j=0;
cnt++;
}
}
return cnt;
}
int main()
{ while(scanf("%s",s1)!=EOF)
{ cnt=0;
if(s1[0]=='#'&&s1[1]=='\0')
break;
scanf("%s",s2);
int n=strlen(s1);
int m=strlen(s2);
net(m);
cout<<kmp(n,m)<<endl;
}
return 0;
}
本文介绍了一种用于字符串匹配的高效算法——KMP算法,并通过一个具体的实现案例详细展示了如何使用KMP算法来查找一个字符串中包含另一个模式串的所有不重叠实例的数量。文章首先定义了next数组的概念,接着介绍了如何通过此数组优化匹配过程,避免不必要的回溯。
579

被折叠的 条评论
为什么被折叠?



