数据结构 字串的模式匹配 KMP算法

来源:互联网 发布:php ffmpeg 微信语音 编辑:程序博客网 时间:2024/05/22 07:53
#include <stdio.h>#include <stdlib.h>#define OK          1#define ERROR       0#define OVERFLOW    -2typedef struct{char *ch;int length;}String;void Init_String(String &T){T.ch = NULL;T.length = 0;}int StrAssign(String &T, char *chars){int i;int len;char *p = chars;if (T.ch){free(T.ch);}for (len = 0;*p != '\0'; ++len,++p);if (!len){T.ch = NULL;T.length = 0;}else{T.ch = (char *)malloc(len * sizeof(char));if (!T.ch){exit(OVERFLOW);}for (i=0; i<len; i++){T.ch[i] = chars[i];}T.length = len;}return OK;}void get_next(String T, int next[]){int i = 0;int j = -1;next[0] = -1;while (i<T.length){if (j == -1 || T.ch[i] == T.ch[j]){++i;++j;next[i] = j;}else{j = next[j];}}}int Index_KMP(String S, String T, int pos){int i = pos;int j = -1;int next[255];get_next(T,next);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 + 1 ;}elsereturn 0;}int main(){String S,T;Init_String(S);Init_String(T);StrAssign(S,"abcdefghijklmm");StrAssign(T,"cdef");printf("%d\n",Index_KMP(S,T,0));return 0;}

0 0