#include<assert.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
void Test_next(int lensub, int* next,char*sub)
{
next[0] = -1;
next[1] = 0;
int i = 2;//当前i项
int k = 0;//前一项
while (i < lensub)
{
if (k==-1||sub[i - 1] == sub[k])
{
next[i] = k + 1;
i++;
k++;
}
else
{
k = next[k];
}
}
}
int KMP(const char* str, const char* sub, int pose)
{
assert(str && sub);
int lenstr = strlen(str);
int lensub = strlen(sub);
if (pose<0 || pose>=lenstr)return -1;
if (lenstr < lensub || lenstr == 0 || lensub == 0)return -1;
int* next = (int*)malloc(sizeof(int) * lensub);
assert(next);
Test_next(lensub, next,sub);
int i = pose;//遍历主串
int j = 0;//遍历字串
while (i < lenstr && j < lensub)
{
if (j==-1||str[i] == sub[j])
{
i++;
j++;
}
else
{
j = next[j];
}
if (j >= lensub)return i - j;
}
return -1;
}
int main()
{
printf("%d", KMP("abcdefasdsd", "efa", 0));
return 0;
}
KMP算法代码
最新推荐文章于 2024-08-08 15:12:59 发布