KMP算法
这个算法看了。很久啊。很难懂。。虽说现在会了。。不过。应用的根本不熟练
老规矩。。。贴下代码。。纪念下。
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { char *ch; int length; }SString; int strKMP(SString *S,SString *T,int pos,int next[]); //求在主窜中S中第pos个字符之后的位置的KMP算法 void get_next(SString *T,int next[]); //求模式串中T的next函数值并存入数组next int StrAssign(SString *str,char *chars); ///生成一个与chars相等的字符串 int main() { SString S={NULL,0},T={NULL,0}; int pos; int next[50]; StrAssign(&S,"ababcabcacbab"); StrAssign(&T,"cacba"); get_next(&T,next); pos=strKMP(&S,&T,0,next); printf("%d\n",pos); return 0; } int StrAssign(SString *str,char *chars) { if(str->ch) //清空str free(str->ch); str->ch = (char *)malloc((strlen(chars)+1)*sizeof(char)); if( !str->ch ) return 0; str->length = strlen(chars); strcpy(str->ch,chars); //复制字符串 return str->length; } int strKMP(SString *S,SString *T,int pos,int next[]) { int i=pos,j=0; while(i < S->length && j < T->length) { if(j==-1 || S->ch[i] == T->ch[j]) { i++; j++; } else j = next[j]; } if(j >= T->length) return i - (T->length); else return -1; } void get_next(SString *T,int next[]) { int i=0,j=-1; next[0]=-1; while(i < T->length-1) //这里注意下 { if(j==-1 || T->ch[i] == T->ch[j]) { i++; j++; if(T->ch[i] != T->ch[j]) next[i]=j; else next[i] = next[j]; } else j = next[j]; } }