题意:
给两个串,问第二个串能在第一个串里面匹配多少次,不可重叠
(hdu2087)
Sample Input
abcde a3
aaaaaa aa
Sample Output
0
3
code:
hdu2087
#include<bits/stdc++.h>
using namespace std;
const int maxm=1e5+5;
char a[maxm],b[maxm];
int lena,lenb;
int nt[maxm];
void getnext(){
int i=0;
int j=nt[0]=-1;
while(i<lenb){
if(j==-1||b[i]==b[j]){
i++,j++;
nt[i]=j;
}else{
j=nt[j];
}
}
}
void kmp(){
getnext();
int ans=0;
int i=0,j=0;
while(i<lena){
if(j==-1||a[i]==b[j]){
i++,j++;
}else{
j=nt[j];
}
if(j==lenb){
ans++;
j=0;//如果是可重叠就改成j=nt[j]
}
}
printf("%d\n",ans);
}
signed main(){
while(scanf("%s",a)!=EOF&&a[0]!='#'){
scanf("%s",b);
lena=strlen(a);
lenb=strlen(b);
kmp();
}
return 0;
}