推荐两篇文章:---1---,---2----
//顺序表KMP算法
int pMatch(PSeqString t,pSeqString p,int *next){
int i,j;
i = 0;
j = 0;
while(i < p->n && j < t->n){
if(i == -1 || p->c[i] == t->c[i]){
i++;
j++;
}else{
i = next[i];
}
}
if(i >= p->n){
return (j-p->n+1);
}else{
return -1;
}
}
//求next数组((未优化之前))
makeNext(PSeqString p,int *next){
int i = 0;
int k = -1;
next[0] = -1;
while(i < p->n-1){
while(k >= 0 && p->c[i] != p->c[k]){
k = next[k];
}
i++;
k++;
next[i] = k;
}
}
//求next数组(优化后)
makeNext(PSeqString p,int *next){
int i = 0;
int k = -1;
next[0] = -1;
while(i < p->n-1){
while(k >= 0 && p->c[i] != p->c[k]){
k = next[k];
}
i++;
k++;
}
if(p->c[i] == p->c[k]){
next[i] = next[k];
}else{
next[i] = k;
}
}