1. 程式人生 > >拓展KMP模板

拓展KMP模板

博主連結

#include<bits/stdc++.h>
using namespace std;
const int maxn=100010;//字串長度最大值 
int next[maxn],ex[maxn];//ex陣列即為extend陣列
char s[maxn],s2[maxn];
int n;
//預處理計算next陣列
void getnext(){
	int i=0,j,po,len=strlen(s);
	next[0]=len;//初始化next[0]
	while(s[i]==s[i+1]&&i+1<len)//計算next[1]
	i++;
	next[1]=i;
	po=
1;//初始化po的位置 for(i=2;i<len;i++){ if(next[i-po]+i<next[po]+po)//第一種情況,可以直接得到next[i]的值 next[i]=next[i-po]; else //第二種情況,要繼續匹配才能得到next[i]的值 { j=next[po]+po-i; if(j<0)j=0;//如果i>po+next[po],則要從頭開始匹配 while(i+j<len&&s[j]==s[j+i])//計算next[i] j++; next[i]=j; po=i;//更新po的位置
} } } //計算extend陣列 void extend(){ int i=0,j,po,len=strlen(s),l2=strlen(s2); getnext();//計運算元串的next陣列 while(s[i]==s2[i]&&i<len)i++; ex[0]=i; po=0;//初始化po的位置 for(i=1;i<len;i++){ if(next[i-po]+i<ex[po]+po) ex[i]=next[i-po];//第一種情況 else{ j=ex[po]+po-i; if(j<0)j=0;//如果j>ex[po]+po則從頭開始匹配
while(i+j<len&&j<<l2&&s[j+i]==s2[j])//計算ex[i] j++; ex[i]=j; po=i; } } } int main(){ }