比较裸的KMP
#include<iostream> #include<algorithm> using namespace std; int n,m; char T[1000010],P[10010]; int nxt[10010]; int KMP() { nxt[0] = -1; int k = -1; for(int q=1;q<=m-1;q++){ while (k > -1 && P[k+1] != P[q]) k = nxt[k]; if (P[k+1] == P[q]) ++k; nxt[q] = k; } int pos = -1; int j = -1,i = 0,count = 0; while (i < n) { while (j > -1 && P[j+1] != T[i]) j = nxt[j]; if (P[j+1] == T[i]) ++j; if (j+1 == m) { count++; j = nxt[j]; } ++i; } return count; } int main() { int cas; scanf("%d",&cas); while(cas--) { scanf("%s %s",P,T); n=strlen(T); m=strlen(P); printf("%d\n",KMP()); } return 0; }