求模式串在待匹配串的出现次数。Input
第一行是一个数字T,表明测试数据组数。 之后每组数据都有两行:第一行为模式串,长度不大于10000;第二行为待匹配串,长度不大于1000000。所有字符串只由大写字母组成。Output
每组数据输出一行结果。Sample Input
4 ABCD ABCD ABA ABABABA CDCDCDC CDC KMP NAIVESample Output
1 3 0 0
求子串在原串中出现的次数,
具体看 KMP算法
#include <bits/stdc++.h> using namespace std; char s[10009],t[1000009]; int lens,lent,f[10009]; void init(){ scanf("%s",s); scanf("%s",t); lens = strlen(s); //这个是子串, lent = strlen(t);//这个是整串, f[0] = -1; //字符串都从0开始,所以,f 的值是前后子串匹配所在的位置。如果是长度的话,,+1 就行。 for (int i = 1; i < lens; i++){ int j = f[i-1]; while(s[j+1] != s[i] && j != -1) j = f[j]; if (s[j+1] == s[i]) f[i] = j+1; else f[i] = -1; } return ; } void Query(){ int i = 0,j = 0,Ans = 0; while(i < lent){ if (t[i] == s[j]){ i++; j++; if (j == lens){ //此时是已经找到完全匹配的字符串了。 Ans++; j = f[j-1]+1; } } else if (j == 0) i++; else j = f[j-1] + 1; } printf("%d\n",Ans); return ; } int main() { int tt; cin>>tt; while(tt--){ init(); Query(); } return 0; }