#ifdef _GETNEXT_
#define _GETNEXT_
#include<cstring>
using namespace std;
int* getNext(char s[] , int len)
{
int j = -1;
int* next = new int [len];
next[0] = -1;
for(int i = 1 ;i < len ; i ++)
{
while(j != -1 && s[i] != s[j + 1])
{
j = next[i];
}
if(s[i] == s[j + 1])
{
j++;
}
next[i] = j;
}
return next;
}
bool KMP(char text[] , char pattern[])
{
int n = strlen(text),m = strlen(pattern);
int * next = getNext(pattern,m);
int j = -1;
for(int i = 0; i < n ;i ++)
{
while(j != -1 && next[i] != pattern[j + 1])
{
j = next[j];
}
if(text[i] == pattern[j+1])
{
j++;
}
if(j == m-1)
{
return true;
}
}
delete next;
return false;
}
#endif
KMP算法
最新推荐文章于 2024-11-16 09:45:51 发布