链接:
http://poj.org/problem?id=3461
代码:
31 char a[MAXN], b[MAXN]; 32 int Next[MAXN]; 33 int sum; 34 35 void buildNext(char P[]) { 36 int m = strlen(P); 37 int i = 0, j; 38 j = Next[0] = -1; 39 while (i < m) { 40 while (-1 != j && P[i] != P[j]) j = Next[j]; 41 Next[++i] = ++j; 42 } 43 } 44 45 void kmp(char P[], char T[]) { 46 int n = strlen(T), i = 0; 47 int m = strlen(P), j = 0; 48 buildNext(P); 49 while (i < n) { 50 while (-1 != j && T[i] != P[j]) j = Next[j]; 51 i++, j++; 52 if (j >= m) sum++, j = Next[j]; 53 } 54 } 55 56 int main() { 57 int T; 58 cin >> T; 59 while (T--) { 60 sum = 0; 61 memset(Next, 0, sizeof(Next)); 62 scanf("%s%s", a, b); 63 kmp(a, b); 64 cout << sum << endl; 65 } 66 return 0; 67 }