首页 > 代码库 > KMP、扩展KMP、Manacher模板

KMP、扩展KMP、Manacher模板

推导过程推荐看这篇

KMP模板:

 1 void init(){
 2     int j = nex[0] = -1, i = 0;
 3     int len = strlen(str);
 4     while(i < len){
 5         if(j == -1 || str[i] == str[j]){
 6             nex[++i] = ++j;
 7         }else j = nex[j];
 8     }
 9 }
10 int KMP(){
11     int i  = 0, j = 0, sum = 0;
12     int len = strlen(str), len1 = strlen(str1);
13     while(j < len1){
14         if(i == -1 || str[i] == str1[j]){
15             i++;j++;
16         }else i = nex[i];
17         if(i == len) sum++;
18     }
19     return sum;
20 }

 

 

 推导详细过程推荐看这篇,通俗易懂:

扩展KMP模板:

 1 void init(){
 2     int len = strlen(str1),a,p;
 3     nex[0] = len;
 4     for(int i = 1, j = -1; i < len; i ++, j--){
 5         if(j < 0 || i+nex[i-a] >= p){
 6             if(j < 0)
 7                 p=i,j=0;
 8             while(p < len && str1[p]==str1[j])
 9                 p++,j++;
10             nex[i] = j;
11             a = i;
12         }else nex[i] = nex[i-a];
13     }
14 }
15 void EKMP(){
16     int a,p;
17     int len = strlen(str), len1 = strlen(str1);
18     for(int i = 1, j = -1; i < len; i++,j--){
19         if(j<0 || i+nex[i-a] >= p){
20             if(j < 0)
21                 p=i,j=0;
22             while(p < len && str[p]==str1[j])
23                 p++,j++;
24             extend[i] = j;
25             a = i;
26         }else extend[i] = nex[i-a];
27     }
28 }

 

 

 这个推导过程较简单,网上很多博客都可以快速看懂的。

Manacher模板:

 1 int Manacher(){
 2     int ans = 0, id = 0, len = strlen(str);
 3     for(int i = len; i >= 0; i --){
 4         str[i+i+2] = str[i];
 5         str[i+i+1] = #;
 6     }
 7     str[0] = *;
 8     for(int i = 2; i<2*len+1; i ++){
 9         if(p[id] + id > i) p[i] = min(p[2*id-i],p[id]+id-i);
10         else p[i] = 1;
11         while(str[i-p[i]] == str[i+p[i]])++p[i];
12         if(p[id] + id < p[i]+i) id = i;
13         if(ans < p[i]) ans = p[i];
14     }
15     return ans-1;
16 }

 

KMP、扩展KMP、Manacher模板