hiho1015 KMP算法

Input

第一行一个整数N,表示测试数据组数。

接下来的N*2行,每两行表示一个测试数据。在每一个测试数据中,第一行为模式串,由不超过10^4个大写字母组成,第二行为原串,由不超过10^6个大写字母组成。

其中N<=20

Output

对于每一个测试数据,按照它们在输入中出现的顺序输出一行Ans,表示模式串在原串中出现的次数。

Sample Input

5
HA
HAHAHA
WQN
WQN
ADA
ADADADA
BABABB
BABABABABABABABABB
DAD
ADDAADAADDAAADAAD

Sample Output

3
1
3
1
0

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cstring>
 5 #include <cstdlib>
 6 #include <string>
 7 
 8 using namespace std;
 9 
10 int n, nxt[2000010];
11 
12 string S, T, W;
13 
14 int main() {
15     ios::sync_with_stdio(false);
16     cin >> n;
17     while(n --) {
18         cin >> S >> T;
19         int ans = 0;
20         W = S + "." + T;
21         for(int i = 1, j = 0 ; i < W.length() ; i ++) {
22             while(j && W[i] != W[j]) j = nxt[j];
23             if(W[i] == W[j]) j ++;
24             nxt[i + 1] = j;
25         }
26         for(int i = S.length() ; i <= W.length() ; i ++) {
27             if(nxt[i] == S.length()) {
28                 ans ++;
29             }
30         }
31         cout << ans << endl;
32     }
33 }
View Code

 



posted @ 2017-08-13 21:00  KingSann  阅读(144)  评论(0编辑  收藏  举报