裸KMP,没啥好讲的。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <malloc.h>
#include <queue>
#include <stack>
using namespace std;
char a[1005],b[1005];
int alen,blen,next[1005];
void getnext(char *s,int *next)
{
int i=1,j=0;
next[1]=0;
while(i<blen)
{
if(j==0||s[i]==s[j])
{
i++;
j++;
if(s[i]==s[j])
next[i]=next[j];
else
next[i]=j;
}
else
{
j=next[j];
}
}
}
int kmp(char *p,char *q,int *next)
{
int k=0,j=0,num=0;
while(k<=alen)
{
if(j==0||p[k]==q[j])
{
if(j==blen)
{
j=0;
num++;
}
k++;
j++;
}
else
{
j=next[j];
}
}
return num;
}
int main()
{
int next[1005];
while(scanf("%s",a+1),a[1]!='#')
{
scanf("%s",b+1);
alen=strlen(a+1);
blen=strlen(b+1);
getnext(b,next);
printf("%d\n",kmp(a,b,next));
}
return 0;
}