题目链接:poj 3461
代码:
#include<cstdio> #include<cstring> #include<iostream> using namespace std; #define MAXN 1000010 char T[10010], S[MAXN]; int len_t, len_s; int next[10010]; void getNext() { int k = -1, j = 0; next[0] = -1; while(j < len_t){ if(k == -1 || T[j] == T[k]){ ++j; ++k; next[j] = k; } else k = next[k]; } } int KMP_Index()//T是模式串,S是 主串 { int i = 0, j = 0; getNext(); while(j < len_t && i < len_s){ if(j == -1 || T[j] == S[i]){ i++; j++; } else j = next[j]; } if(j == len_t){ return i - len_t; } else return -1; } int KMP_Count() { int ans = 0; int i = 0, j = 0; if(len_s == 1 && len_t == 1){ if(S[0] == T[0])return 1; else return 0; } getNext(); for(i = 0; i < len_s; i++) { while(j > 0 && T[j] != S[i]){ j = next[j]; } if(T[j] == S[i]) j++; if(j == len_t){ ans++; j = next[j]; } } return ans; } int main() { int t; cin >> t; while(t--){ scanf("%s%s", &T, &S); len_s = strlen(S); len_t = strlen(T); printf("%d\n", KMP_Count()); } return 0; }