KMP算法可以说是BF算法的升级版
BF算法i回退,但是KMP算法最大的特点就是i不回退,由于i不会退,所以KMP算法的时间复杂度为O(n+m)
公式证明
![](https://img-blog.csdnimg.cn/direct/1fca5783c6fe4de1824fe98a0465b7ba.png)
匹配成功的子串中找到两个最长的相等的真子串,这两个真子串满足一下特点
(1)一个串以子串的开头作为开头
(2)另一个串以失配前的最后一个字符作为结尾(Pj-1)
(3)k正是子串的长度
next数组
我们把所有位置的K值给保存在数组中,这个数组就是next数组
KMP算法的特点
指示主串的指针不需要回溯,整个匹配过程中,对主串仅仅需要从头到尾扫描一遍。这对处理从外设输入的庞大文件很有效,可以边读入边匹配,而无需回头重读
KMP算法实现
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<assert.h>
static int* GetNext(const char* str)
{
int len = strlen(str);
int* next = (int*)malloc(len * sizeof(int));
next[0] = -1;
next[1] = 0;
int j = 1;
int k = 0;
while (j + 1 < len)
{
if ((k == -1) || str[k] == str[j])
{
next[++j] = ++k;
}
else
{
k = next[k];
}
}
return next;
}
int KMP(const char* str, const char* sub, int pos)
{
assert(str != NULL);
if (str == NULL || sub == NULL)
return -1;
if (pos > strlen(str)||pos<0)
return -1;
if (strlen(sub) > strlen(str))
return -1;
int lenstr = strlen(str);
int lensub = strlen(sub);
int i = pos;
int j = 0;
int* next = GetNext(sub);
while (i < lenstr && j < lensub)
{
if ((j==-1)||str[i] == sub[j])
{
i++;
j++;
}
/*else
{
pos++;
i = pos;
j = 0;
}*/
else
{
j = next[j];
}
}
free(next);
//if (sub[j] == '\0')
// return pos;
if (j >= lensub)
return i - j;
else
return -1;
}
int main()
{
const char* str1 = "ababcabcdabcde";
const char* str2 = "abcd";
const char* str3 = "abc";
printf("%d ", KMP(str1, str2, 0));
printf("%d ", KMP(str1, str2, 5));
printf("%d ", KMP(str1, str2, 9));
return 0;
}