KMP算法分两步:
1、求解模式串的next数组
2、当模式串中的字符和目标串中的字符失配时,利用模式串的next数组对模式串进行右移
因此要实现KMP算法,首先要求解next数组:
next数组中保存的是当前字符之前的字符段里前缀和后缀相同的长度,例如
模式串为: ABCDABD
next数组为:-1 0 0 0 0 1 2
求解的过程为:
1、首先给next[0]置成-1,然后递推的求解next[i],即i之前的数都已求得
2、如果pattern[i-1] == pattern[next[i-1]],那么next[i]=next[i-1]+1,
如果pattern[i-1] != pattern[next[i-1]],那么就去寻找更短的前后缀相同的字符段,即验证pattern[i-1]是否等于pattern[next[next[i-1]]],直到找到前后缀相同或者找到模式串头。
c++代码实现为:
int * GetNextArray(
const
string pattern){
int * next = new int[pattern.size()];
next[ 0] = - 1;
int compare_index;
for ( int i= 1;i<pattern.size();i++){
compare_index = next[i- 1];
while(compare_index != - 1 && pattern [compare_index ] != pattern [i- 1 ]){
compare_index = next[compare_index];
}
next[i] = compare_index + 1;
}
return next;
int * next = new int[pattern.size()];
next[ 0] = - 1;
int compare_index;
for ( int i= 1;i<pattern.size();i++){
compare_index = next[i- 1];
while(compare_index != - 1 && pattern [compare_index ] != pattern [i- 1 ]){
compare_index = next[compare_index];
}
next[i] = compare_index + 1;
}
return next;
}
第二步,利用next数组对模式串进行移动:
例如当用ABCDABD作为模式串,去字符串里寻找是否匹配时,
BBC ABCDAB ABCDABCDABDE
ABCDABD
ABCDABD
ABCDABD
D在当前位置失配,由于D之前的部分都是可以匹配的,因此查找next[6]的值,发现D之前有长度为2的前缀后缀相同部分,那么向右移动模式串,移动6-next[6]个位置,此时C和目标串中下标为10的字符检查是否匹配,再次发现失配,查找next[2]的值,向右移动模式串,移动2-next[2]个位置,检查A和目标串中下标为10的字符是否匹配,继续失配,查找next[0]的值,next[0]的值为-1,此时应用目标串中下标为11的字符和模式串中下标为0的字符检查是否匹配了。
c++代码实现为:
int StringMatch(
const
string str,
const
string pattern){
int * next = GetNextArray(pattern);
int j = 0;
int match_begin = - 1;
for( int i= 0;i<str.size();i++){
while(str [i ]!=pattern [j ] && j!=- 1){
j = next[j];
}
if(j == pattern.size()- 1){
match_begin = i;
match_begin = i-j;
break;
}
j++;
}
return match_begin;
}
int * next = GetNextArray(pattern);
int j = 0;
int match_begin = - 1;
for( int i= 0;i<str.size();i++){
while(str [i ]!=pattern [j ] && j!=- 1){
j = next[j];
}
if(j == pattern.size()- 1){
match_begin = i;
match_begin = i-j;
break;
}
j++;
}
return match_begin;
}