next[i]:字符串a中以a[i]结尾的后缀子串与前缀子串的最大匹配长度。
1 2 3 4 5 6 7 8
a b c a b c m a
0 0 0 1 2 3 0 1
可重叠代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
typedef unsigned long long ull;
const int N=1e6+10;
char a[N],b[N];
int next1[N];
int n,m;
int f[N];
void get()
{
next1[1]=0;
int j=0;
for(int i=2;i<=n;i++)
{
while(j>0&&a[i]!=a[j+1]) j=next1[j];
if(a[i]==a[j+1]) j++;
next1[i]=j;
}
}
int main()
{
while(cin>>b+1>>a+1)//从1开始
{
int cnt=0;
n=strlen(a+1);
m=strlen(b+1);
get();
int j=0;
for(int i=1;i<=m;i++)
{
while(j&&(b[i]!=a[j+1])) j=next1[j];
if(b[i]==a[j+1]) j++;
if(j==n)//完整出现一次就记录一次,同时把长度回溯
cnt++,j=next1[j];
}
cout<<cnt<<endl;
}
return 0;
}
查找的字串不可以重叠的话就把上面代码里面的
cnt++,j=next1[[j]; 改为 cnt++,j=0;