KMP算法
KMP算法通常需要一个部分匹配表(Partial Match Table)。用next数组保存部分匹配值,也就是前 i 个字符所组成的子串的真前缀与真后缀相同的最大长度。当发生不匹配时,直接从next数组保存的索引开始匹配,忽略不必要的匹配操作。
真前缀
真前缀,指字符串首部开始的除了最后一个字符的所有子串。
例如"abcde"的真前缀有[a,ab,abc,abcd]
真后缀
真后缀,指字符串尾部开始的除了第一个字符的所有子串。
例如"abcde"的真后缀有[bcde,cde,de,e]
真前缀与真后缀相同的最大长度
例如"ababa"的真前缀为[a,ab,aba,abab],真后缀为[baba,aba,ba,a],其中相同的最长子串为"aba" 即最大长度为3。
next表格:
A | B | A | B | C | A | B | A | A |
---|---|---|---|---|---|---|---|---|
-1 | 0 | 1 | 2 | 0 | 1 | 2 | 3 | 1 |
求next表格的相关代码:
- 求其前缀表(
void next_table(char pattern[],int next[],int n){
next[0] = 0;
int l = 0;
int i = 1;
while(i<n){
if(pattern[i] == pattern[l]){
l ++;
next[i] = l;
i ++;
}
else{
if(l > 0){
l = next[l-1];
}
else{
next[i] = l;
i++;
}
}
}
//cout << "nnn";
return;
}
2.后移一位
void move(int next[],int n){
int i;
for(i = n-1;i>0;i--){
next[i] = next[i-1];
}
next[0] = -1;
}
KMP查找代码:
void kmp(char text[],char pattern[]){
int n = strlen(pattern);
int m = strlen(text);
int next[N];
next_table(pattern,next,n);
move(next,n);
int i=0;
int j=0;
// for(int i=0;i<n;i++){
// cout << next[i] << " ";
// }
while(i<m){
//cout <<i << "-----" <<m <<"---"<< j<<endl;
if(j==n-1&&text[i]==pattern[j]){
printf("found pattern at %d\n",i-j);
j = next[j];
break;
}
if(text[i]==pattern[j]){
i++;
j++;
}
else{
j = next[j];
if(j==-1){
i++;j++;
}
}
}
return;
}
洛谷例题:
P3375
P4391(主要对next数组的理解)