核心
算法核心是回溯子串指針,回溯值從子串next數組找出。相比較樸素的字符串匹配算法,主串指針不再回溯,子串next數組由子串前綴後綴重複字母數量確定。
#include <stdio.h>
#include <string.h>
void get_next(char* T,int *next){
int i,j;
i=1;
j=0;
next[1]=0;
while(i<strlen(T)){
if(j==0 || T[i]==T[j]){
i++;
j++;
next[i]=j;
}
else{
j=next[j]; //j值回溯
}
}
}
int Index_KMP(char* S,char* T,int pos){
int i=pos;
int j=1;
int next[255];
get_next(T,next);
while(i<=strlen(S)&&j<=strlen(T)){
if(j==0 || S[i]==T[j]){
++i;
++j;
}
else{
j=next[j];
}
}
if(j>strlen(T))
return i-strlen(T)-1;
else
{
return 0;
}
}
int main(void){
char* s1="hello,world";
char* s2="world";
int index=Index_KMP(s1,s2,0);
printf("%d\n",index);
return 0;
}