KMP

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<string>
 5 #include<memory.h>
 6 using namespace std;
 7 
 8 int count = 0;
 9 string s,l;
10 
11 void get_next(string src, int m, int *next)
12 {
13     int i = 0,j = -1;
14     next[0] = j;
15     while (i < m) {
16         while (j != -1 && src[j] != src[i])
17             j = next[j];
18         i++,j++;
19         next[i] = j;
20     }
21 }
22 
23 void kmp(string s,int m, string l, int n)
24 {
25     int next[10005];
26     get_next(s,m,next);
27     int i = 0,j = 0;
28     while (i < n) {
29         while (j != -1 && s[j] != l[i])
30             j = next[j];
31         i++,j++;
32         if (j == m){
33             count++;
34             j = next[j];
35         }
36     }
37 }
38 int main()
39 {
40     int t;
41     cin >> t;
42     while (t--) {
43         count = 0;
44         cin >> s >> l;
45         kmp(s,s.length(),l,l.length());
46         cout << count << endl;
47     }
48     return 0;
49 }
代码君

 

介绍有很多,觉得真正写得好,容易懂的博客:

http://blog.csdn.net/guo_love_peng/article/details/6618170

 

posted @ 2014-12-13 16:20  UsedRose  阅读(109)  评论(0编辑  收藏  举报