KMP的实现

来源:互联网 发布:房地产数据分析职位 编辑:程序博客网 时间:2024/06/05 06:23
#include <iostream>using namespace std;int* buildNext(char * p){size_t m = strlen(p), j = 0;int *Next = new int[m];int t = Next[0] = -1;//模式串指针while (j<m - 1) {if (t<0 || p[j] == p[t]) {Next[++j] = ++t;}else{t = Next[t];}}return Next;}int KMP(char* p, char *T){int *next = buildNext(p);//构造next表int n = (int)strlen(T), i = 0;//文本串指针int m = (int)strlen(p), j = 0;//模式串指针while (i<n&&j<m){if (j<0 || T[i] == p[j]) {i++; j++;}else{j = next[j];}}delete[] next;return i - j;}int main(int argc, const char * argv[]) {cout<<KMP("abcdefg","cde");return 0;}
0 0