纯KMP
1 #include <cstdio> 2 #include <algorithm> 3 #include <cstring> 4 #include <ctype.h> 5 #include <cstdlib> 6 #include <stack> 7 #include <set> 8 #include <map> 9 #include <queue> 10 #include <string> 11 #include <cmath> 12 13 14 15 using namespace std; 16 17 int M,N,T; 18 char A[1000100],B[10100]; 19 int f[10100]; 20 21 void getFail(char *P) 22 { 23 f[0] = 0;f[1] = 0; 24 for(int i=1;i<M;i++) 25 { 26 int j = f[i]; 27 while(j && P[i] != P[j]) j = f[j]; 28 f[i+1] = P[i] == P[j] ? j+1 : 0; 29 } 30 } 31 32 int find(char *T,char *P) 33 { 34 getFail(P); 35 int j=0; 36 int ans = 0; 37 for(int i=0;i<N;i++) 38 { 39 while(j && T[i] != P[j]) j = f[j]; 40 if( T[i] == P[j] ) j++; 41 if(j == M) {i += M-1;ans++;} 42 } 43 return ans; 44 } 45 46 47 int main() 48 { 49 50 while(2 == scanf("%s %s",A,B)) 51 { 52 N = strlen(A);M = strlen(B); 53 printf("%d ",find(A,B)); 54 } 55 }