http://www.ituring.com.cn/article/59881
http://blog.csdn.net/v_july_v/article/details/7041827
http://blog.csdn.net/v_july_v/article/details/7041827
http://www.cnblogs.com/mfryf/archive/2012/08/15/2639565.html
problem:http://acm.hdu.edu.cn/showproblem.php?pid=2087
kmp计数
#include <bits/stdc++.h> using namespace std; #define maxn 1010 char str[maxn],son[maxn]; int nxt[maxn]; void init(int len) { int i = 0, j = -1; nxt[0] = -1; while (i < len ) { if (j == -1 ||son[i] == son[j]) { i++; j++; nxt[i] = j; } else j = nxt[j]; } } void kmp() { int i = 0, j = 0, ans = 0; int lt = strlen(str), lp = strlen(son); init(lp); while (i < lt) { if (j == -1 || str[i] == son[j]) { i++; j++; } else j = nxt[j]; if (j ==lp) { ans++; j = 0; } } printf("%d\n", ans); } int main() { while (scanf("%s%s", str, son) == 2) { kmp(); } return 0; }