Kmp 加深理解 之 poj 3461
// [9/11/2014 Sjm]
/*
求模式串在文本中出现的次数。。。
关键在于:在计算过第一次匹配位置后时,利用 next[模式串.size()] 去继续计算。。。
详见代码注释。。。。
*/
1 #include <iostream> 2 #include <cstdlib> 3 #include <cstdio> 4 #include <string> 5 using namespace std; 6 int N, M, next[10005]; 7 string S, T; 8 9 void getNext() { 10 int j = 0, k = -1; 11 next[0] = -1; 12 while (j < M) { 13 if ((-1 == k) || (T[j] == T[k])) { 14 ++j; ++k; // 注意:next[M] 的值是存在的(T[M] = '\0') 15 if (T[j] != T[k]) next[j] = k; 16 else next[j] = next[k]; 17 }else k = next[k]; 18 } 19 } 20 21 int Solve() { 22 getNext(); 23 int i = 0, j = 0, ans = 0; 24 while (i < N) { 25 if ((-1 == j) || (S[i] == T[j])) { 26 ++i; ++j; 27 if (M == j) { 28 ++ans; 29 j = next[j]; // 据next[M] 的值继续计算 30 } 31 }else j = next[j]; 32 } 33 return ans; 34 } 35 36 int main() { 37 //freopen("input.txt", "r", stdin); 38 int Case; 39 scanf("%d", &Case); 40 while (Case--) { 41 cin >> T >> S; 42 N = S.size(); M = T.size(); 43 printf("%d\n", Solve()); 44 } 45 return 0; 46 }