C语言:串的模式匹配算法

BF算法(穷举):
inti=pos;//i用于主串parent中的起始位置
intj=1;//子串的起始位置
while(i<=parent->length&&j<=child->length){
if(parent->ch[i-1]==child->ch[j-1]){
i++;
j++;
}else{
i=i-j+2;//i回朔到上次匹配的首位的下一位
j=1;//j回到子串的第一个位置
}
}
if(j>child->length){
returni-child->length;
}
return0;
}
KMP算法(不回溯指针i,利用部分匹配值将指针向右滑到尽可能远的距离,速度快):
部分匹配值的计算:
inti=0;
intj=-1;
next[0]=-1;
while(i<child.length){
if(j==-1||child.ch[i]==child.ch[j]){
++i;
++j;
next[i]=j;
}else{
j=next[j];
}
}
KMP算法实现时与BF算法区别
else{
j=next[j];//
}
}
if(j==child->length){
return(i+1)-j;
}