KMP 专栏6的I题
有空再写题解
#include <bits/stdc++.h>
using namespace std;
int nexxt[100];
void GetNext(char* p,int nexxt[]) {
int pLen = strlen(p);
nexxt[0] = -1;
int k = -1;
int j = 0;
while (j < pLen - 1) {
if (k == -1 || p[j] == p[k]) {
++k;
++j;
nexxt[j] = k;
} else {
k = nexxt[k];
}
}
}
int KmpSearch(char* s, char* p) {
int i = 0;
int j = 0;
int sLen = strlen(s);
int pLen = strlen(p);
int num = 0;
while (i < sLen) {
if (j == -1 || s[i] == p[j]) {
i++;
j++;
}
else {
j = nexxt[j];
}
if (j == pLen)
num++;
}
return num;
}
int main() {
char a[1005],b[1005];
while(scanf("%s",a)!=EOF) {
if(a[0] == '#') break;
scanf("%s",b);
GetNext(b,nexxt);
int c = KmpSearch(a,b);
printf("%d\n",c);
}
}