前提
推荐阅读彻底搞懂KMP算法原理
本文采用下标0开始的数组来实现next数组,下标1开始的代码以注释表示。
主串:ababcabcacbab
模式串:abcac
计算所得next数组:-1 0 0 0 1
next数组代码:
void get_next(int next[],char str[]){
next[0]=-1;//next[1]=0
int i,j;
i=0,j=-1;//i=1,j=2;
while(i<strlen(str)){
if(j==-1||str[i]==str[j]){//(j==0||str[i]==str[j])
next[++i]=++j;
}else{
j=next[j];
}
}
}
查找模式串位置模板
int findPos(char a[],char b[],int pos,int next[]){
//查找子串b在主串a中起始下标,pos为查找起始位
int i,j;
i=pos,j=0;
while(i<strlen(a)&&j<strlen(b)){
if(j==0||a[i]==b[j]) i++,j++;
else j=next[j];
}
if(j<lenB) return -1;//查找失败返回-1
else return i-strlen(b);
}
代码
#include <stdio.h>
#include <string.h>
#define maxsize 100//数组最大长度
char strA[]="ababcabcacbab";//主串
char strB[]="abcac";//模式串
int lenA,lenB;//串长
int kmp[maxsize];//next数组
void get_next(int next[],char str[]){//求next数组
next[0]=-1;//next[1]=0
int i,j;
i=0,j=-1;//i=1,j=2;
while(i<strlen(str)){
if(j==-1||str[i]==str[j]){//(j==0||str[i]==str[j])
next[++i]=++j;
}else{
j=next[j];
}
}
}
int findPos(char a[],char b[],int pos,int next[]){
//查找子串b在主串a中起始下标,pos为查找起始位
int i,j;
i=pos,j=0;
while(i<lenA&&j<lenB){
if(j==0||a[i]==b[j]) i++,j++;
else j=next[j];
}
if(j<lenB) return -1;//查找失败返回-1
else return i-lenB;
}
int main(){
int i,j;
lenA=strlen(strA);
lenB=strlen(strB);
get_next(kmp,strB);
printf("mainString:%s\nSubString:%s\nnextList:",strA,strB);//输出两个串
for(i=0;i<lenB;i++){
printf("%d ",kmp[i]);//输出next数组
}
printf("\nSubList's Position:%d",findPos(strA,strB,0,kmp));//输出下标
return 0;
}
输出数据
mainString:ababcabcacbab
SubString:abcac
nextList:-1 0 0 0 1
SubList's Position:5
后记
设主串和模式串长度分别为m,n
KMP算法的时间复杂度是
O
(
m
+
n
)
O(m+n)
O(m+n),而BF算法的时间复杂度为
O
(
m
n
)
O(mn)
O(mn),但是实际上BF算法在计算机执行时间近似于
O
(
m
+
n
)
O(m+n)
O(m+n),所以BF算法仍然广泛使用,KMP算法比较适合主串和模式串有很多“部分匹配”的情况。