拓展kmp是对KMP算法的扩展,它解决如下问题:
定义母串S,和字串T,设S的长度为n,T的长度为m,求T与S的每一个后缀的最长公共前缀
其中next数组表示T[i,m-1]和T的最长公共前缀
1 const int maxn=100010; //字符串长度最大值 2 int next[maxn],ex[maxn]; //ex数组即为extend数组 3 //预处理计算next数组 4 void GETNEXT(char *str) 5 { 6 int i=0,j,po,len=strlen(str); 7 next[0]=len;//初始化next[0] 8 while(str[i]==str[i+1]&&i+1<len)//计算next[1] 9 i++; 10 next[1]=i; 11 po=1;//初始化po的位置 12 for(i=2;i<len;i++) 13 { 14 if(next[i-po]+i<next[po]+po)//第一种情况,可以直接得到next[i]的值 15 next[i]=next[i-po]; 16 else//第二种情况,要继续匹配才能得到next[i]的值 17 { 18 j=next[po]+po-i; 19 if(j<0)j=0;//如果i>po+next[po],则要从头开始匹配 20 while(i+j<len&&str[j]==str[j+i])//计算next[i] 21 j++; 22 next[i]=j; 23 po=i;//更新po的位置 24 } 25 } 26 } 27 //计算extend数组 28 void EXKMP(char *s1,char *s2) 29 { 30 int i=0,j,po,len=strlen(s1),l2=strlen(s2); 31 GETNEXT(s2);//计算子串的next数组 32 while(s1[i]==s2[i]&&i<l2&&i<len)//计算ex[0] 33 i++; 34 ex[0]=i; 35 po=0;//初始化po的位置 36 for(i=1;i<len;i++) 37 { 38 if(next[i-po]+i<ex[po]+po)//第一种情况,直接可以得到ex[i]的值 39 ex[i]=next[i-po]; 40 else//第二种情况,要继续匹配才能得到ex[i]的值 41 { 42 j=ex[po]+po-i; 43 if(j<0)j=0;//如果i>ex[po]+po则要从头开始匹配 44 while(i+j<len&&j<l2&&s1[j+i]==s2[j])//计算ex[i] 45 j++; 46 ex[i]=j; 47 po=i;//更新po的位置 48 } 49 } 50 }