介绍
KMP算法是解决字符串匹配问题的一种优化算法,时间复杂度为线性的O(m+n)。
应用场景
给定一个字符串string和模式串compile,求解模式串compile在字符串string中的位置
方法一:暴力匹配
如果选用暴力匹配,并假设字符串中匹配到 i 位置,模式串中匹配到 j 位置,则:
- 如果当前字符匹配成功,即string[i]==compile[j],则 i 和 j 自增,继续匹配下一个字符。
- 如果当前字符匹配失败,即string[i]!=compile[j],则i回到原来位置的后一位,j重置到模式串的头部,即i=i-j+1,j=0。
void index_force(char* string, char compile[]) {
int i = 0;
int j = 0;
while (i < strlen(string) && j < strlen(compile)) {
if (string[i] == compile[j])
{
i++;
j++;
}
else
{
i -= j - 1;
j = 0;
}
}
if (j == strlen(compile)) printf("下标为%d", i-j);
else printf("未匹配到数据");
}
方法二:KMP算法
- 求得next数组,可以使用数学推理或者最长相等前后缀来理解
void get_next(char* compile, int next[]) {
next[0] = -1;
int i = 0;
int j = -1;
while (i < strlen(compile)) {
if (j==-1||compile[i] == compile[j]) {
i++;
j++;
if (compile[i] != compile[j])
next[i] = j;
else
//对next数组进行优化
next[i] = next[j];
}
else
j = next[j];
}
}
- 进行匹配
void index_KMP(char* string, char compile[],int pos) {
int i = pos;
int j = 0;
int next[9] = {};
get_next(compile, next);
while (i<strlen(string) && j<strlen(compile))
{
if (compile[j] == string[i]) {
i++;
j++;
}
else {
next[j] == -1 ? i++, j=0 :j=next[j] ;
}
}
if (j == strlen(compile))
printf("下标为%d", i - strlen(compile));
else
printf("未找到");
}