KMP算法
基本思想:
求next数组:
代码实现:
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
static void GetNext(const char *str,int *next)
{
int len = strlen(str);
next[0] = -1;
next[1] = 0;
int j = 1;
int k = 0;
while(j + 1 < len)
{
if((k == -1) || (str[k] == str[j]))//Pk == Pj
{
next[++j] = ++k;
}
else//Pk != Pj
{
k = next[k];//k相当于KMP中的j
}
}
}
int KMP(const char *str,const char *sub,int pos)//O(m+n)
{
assert(str != NULL && sub != NULL && pos >= 0);
int i = pos;
int j = 0;
int lenstr = strlen(str);
int lensub = strlen(sub);
int *next = (int *)malloc(lensub *sizeof(int));
GetNext(sub,next);
while(i < lenstr && j < lensub)
{
if((j == -1) || (str[i] == sub[j]))
{
i++;
j++;
}
else
{
j = next[j];//i不用回退
}
}
free(next);
if(j >= lensub)
{
return i - j;
}
else
{
return -1;
}
}
int main()
{
printf("%d\n",KMP("ababcabcdabcde","abcdf",0));
printf("%d\n",KMP("ababcabcdabcde","abcd",4));
printf("%d\n",KMP("ababcabcdabcde","abc",8));
return 0;
}
运行结果: