KMP实现

来源:互联网 发布:用mac怎么该音频格式 编辑:程序博客网 时间:2024/04/29 22:11

KMP最难的部分就是next数组的实现,涉及到数学的证明和对next数组的理解

// KMP.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include "string.h"#include "stdio.h"#define MAX 10char pattern[MAX] = "ABAB";char Str[] = "ABCDABDABCDABD";char next[MAX];//前一个字串的最长前后缀公共串void GetNext(){int pLen = strlen(pattern);      next[0] = -1;      int k = -1;      int j = 0;      while (j < pLen - 1)      {          //p[k]表示前缀,p[j]表示后缀          if (k == -1 || pattern[j] == pattern[k])           {              ++j;              ++k;              next[j] = k;          }          else           {              k = next[k];          }      }  }void KMP(){int len = strlen(Str);int plen = strlen(pattern);int j;for (int i = 0; i < len;){for (j = 0; j < plen; j++){if (Str[i+j] != pattern[j])break;}if (j == plen)printf("find\n");i += j - next[j];}}int main(int argc, char* argv[]){GetNext();KMP();return 0;}


0 0
原创粉丝点击