Create KMP_int.cpp

This commit is contained in:
Kirigaya Kazuto 2016-08-13 12:11:48 +08:00 committed by GitHub
parent b7984113a3
commit 592fa8d5fe

View File

@ -0,0 +1,23 @@
void MakeNext(int* P,int M,int* Next){
Next[0] = -1;
int i = 0, j = -1;
while(i<M){
if(j==-1||P[i]==P[j]){
i++,j++;
if(P[i]!=P[j])Next[i] = j;
else Next[i] = Next[j];
}
else j = Next[j];
}
}
int KMP(int* T,int N,int* P,int M)
{
MakeNext(P,M,Next);
int i=0,j=0;
while(i<N&&j<M){
if(T[i]==P[j]||j==-1)i++,j++;
else j = Next[j];
}
if(j==M)return i-M;
else return -2;
}