题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2087
AC代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
char text[1010];
char patten[1010];
int nex[1010];
void getNext() {
int len = strlen(patten);
nex[0] = -1;
int k = -1,j = 0;
while(j < len) {
if(k == -1 || patten[j]==patten[k]) {
k++;
j++;
nex[j] = k;
}
else {
k = nex[k];
}
}
}
int kmp() {
int cnt = 0,i = 0,j = 0;
int lenp = strlen(patten);
int lent = strlen(text);
while(i < lent) {
if(j == -1 || text[i]==patten[j]) {
i++;
j++;
}
else
j = nex[j];
if(j == lenp) {
j = 0; ///模式串要从头开始进行匹配。
cnt++;
}
}
return cnt;
}
int main() {
while(~scanf("%s",text)) {
if(strcmp(text,"#")==0)
break;
scanf("%s",patten);
getNext();
int ans = kmp();
printf("%d\n",ans);
getchar();
}
return 0;
}