KMP算法:运用于字符串匹配
思想图解:
KMP算法相比于BF算法要快得多,时间复杂度为O(m+n)
代码:
#include<stdio.h>
#include<string.h>
#include<assert.h>
#include<stdlib.h>
void Getnext(int *next,const char *sub)
{
int sublen = strlen(sub);
next[0] = -1;
next[1] = 0;
int i = 2;
int k = 0;
while(i < sublen)//next数组没求完
{
if((k == -1) || (sub[k] == sub[i-1]))
{
/*next[i] = k+1;
i++;
k+=1;*/
next[i++] = ++k;
}
else
{
k = next[k]; //error k = next[i];
}
}
}
int KMP(const char *s,const char*sub,int pos)
{
int i = pos;
int j = 0;
int slen = strlen(s);
int sublen = strlen(sub);
int *next = (int*)malloc(sublen*sizeof(int));
assert(next != NULL);
Getnext(next,sub);
while(i<slen && j<sublen)
{
if((j == -1) || (s[i] == sub[j]))
{
i++;
j++;
}
else
{
j = next[j];
}
}
free(next);
if(j >= sublen)//找到了
{
return i - j;
}
else//匹配失败
{
return -1;
}
}
int main()
{
char *s = "ababcabcdabcde";
char *sub ="abcdf";
printf("%d\n",KMP(s,sub,0));
return 0;
}
测试用例
(1)
S “ababcabcdabcde”
P “abcdf”
(2)
S “ababcabcdabcde”
P “abcd”
(3)
S “ababcabcdabcde”
P “abcd”
KMP(s,sub,6)