kmp模板

KMP的c++版模板

例题 HDU5918  http://acm.hdu.edu.cn/showproblem.php?pid=5918

 1 template<typename first_T, typename second_T>
 2 void kmp_init_next(const first_T *dec,
 3                    int dlen,
 4                    second_T next[]) {
 5     int i, j;
 6     j = next[0] = -1;
 7     i = 0;
 8     while (i < dlen) {
 9         while (-1 != j && dec[i] != dec[j])
10             j = next[j];
11         next[++i] = ++j;
12     }
13 }
14 /*
15 *匹配串 dec 长度 dlen
16 *模式串 tag 长度 tlen
17 *start 匹配串起始匹配位置
18 *step  匹配串递增长度
19 *limit 最大匹配数
20 */
21 template<typename first_T, typename second_T>
22 int kmp_count(const first_T *dec, int dlen,
23               const first_T *tag, int tlen,
24               second_T next[],
25               int start = 0, int step = 1,
26               int limit = 0x3f3f3f3f) {
27 
28     int i, j, ans;
29     i = start;
30     j = ans = 0;
31     while (i < dlen) {
32         while (-1 != j && dec[i] != tag[j])
33             j = next[j];
34         i += step; ++j;
35         if (j >= tlen) {
36             ++ans;
37             if (ans >= limit)   goto result;
38             j = next[j];
39         }
40     }
41 result :
42     return ans;
43 }

猜你喜欢

转载自www.cnblogs.com/zfdyf/p/9033193.html
今日推荐