KMP算法模板

sub[ ]代表子串,str[ ]代表原串,next[ ]代表当sub[i] != str[j]时,子串需要跳到的地方,实现代码如下:

获取next数组的代码:

 1 void GetNext()//求子串中的相同的真前缀和真后缀
 2 {
 3     memset(next, 0, sizeof(next));
 4     next[0] = -1;
 5     int i = 0,j = -1;
 6     int sub_len = strlen(sub);
 7     while(i < sub_len)
 8     {
 9         if(j == -1 || sub[i] == sub[j])
10         {
11             i++;
12             j++;
13             next[i] = j;
14         }
15         else
16             j = next[j];
17     }
18 }

KMP实现的代码:

 1 int KMP()
 2 {
 3     int res = 0;
 4     int sub_len = strlen(sub);
 5     int str_len = strlen(str);
 6     int i = 0;
 7     int j = 0;
 8     while(i < str_len && j < sub_len)
 9     {
10         if(j == -1 || str[i] == sub[j])
11         {
12             i++;
13             j++;
14         }
15         else
16             j = next[j];
17         if(j == sub_len)     //此处实现的是统计子串在原串中出现的次数
18         {                    //这里可以根据具体情况来调整
19             res++;
20             j = next[j];
21         }
22     }
23     return res;
24 }

练习题:Oulipo-Poj

 

posted @ 2018-10-02 19:34  sykline  阅读(104)  评论(0编辑  收藏  举报