kmp算法主要思想为:避免主字符串的回溯,减少子字符串的回溯,利用子字符串的自身已知信息,通过最大相等前缀和后缀的长度定义next数组,从而为子字符串的回溯提供位置信息。
以下是next数组的定义方式:
#include <iostream>
#include <string>
using namespace std;
void getnext(char *t, int *next)
{
int j = 0, k = -1;
int m;
m = strlen(t);
next[0] = -1;
while(j < m-1)
{
if(k == -1 || t[k] == t[j]) //向前匹配;
{
j++;
k++;
next[j] = k; //为next数组赋值;
}
else
k = next[k]; //往前回溯;
}
}
定义完next数组之后,再实现kmp匹配的过程,最后建立主函数进行测试:
int kmpmatch(char *s, char *t)
{
int i = 0, j = 0;
int n = strlen(s);
int m = strlen(t);
int *next = new int[m+1];
getnext(t, next);
while(i < n && j < m)
{
if(j == -1 || s[i] == t[j]) //满足条件则向下一个字符匹配;
{
j++;
i++;
}
else
j = next[j]; //子字符串向前回溯;主字符串下标不变;
}
if(j >= m)
return i - m; //返回子字符串在主字符串中第一次出现的位置;
else
return -1; //没有找到则返回-1;
}
int main()
{
char *str = "ababcabcacb";
char *ptr = "abcac";
cout << str << endl << ptr << endl;
int result = kmpmatch(str, ptr);
if(result == -1)
cout <<"没有匹配结果" << endl;
else
cout << "在第 " << result+1 << " 个字符位置首次出现" << endl;
return 0;
}
上面提供的主要为代码的实现,有关具体思想的解析,提供一位大佬的博客链接以作参考:
https://blog.youkuaiyun.com/starstar1992/article/details/54913261
这个算法可能初看不太容易理解,但是只要耐心细致地了解原理,推演过程,掌握要点后就会变得简单。