给S1和S2,求S1可以分割出多少个互不重叠的S2
裸kmp
#include <cstdio>
int kmp(char s1[],char s2[],int next[]) {
int i,j,k,ans=0;
j=0;k=-1;
next[0]=-1;
while (s2[j]!='\0') {
while (k!=-1&&s2[j]!=s2[k]) k=next[k];
j++;k++;
if (s2[j]!=s2[k]) next[j]=k;
else next[j]=next[k];
}
i=j=0;
while (s1[i]!='\0') {
if (j!=-1&&s2[j]=='\0') {
ans++;
j=0;
} else {
while (j!=-1&&s1[i]!=s2[j]) j=next[j];
i++;j++;
}
}
if (s2[j]=='\0') ans++;
return ans;
}
char s1[100000];
char s2[100000];
int next[100000];
int main() {
while (scanf("%s",s1),s1[0]!='#'||s1[1]!='\0') {
scanf("%s",s2);
printf("%d\n",kmp(s1,s2,next));
}
return 0;
}