KMP算法模板

本文最后更新于:3 years ago

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const int MAXN = 1e5 + 5e2;
int Next[MAXN];
char str1[MAXN], str2[MAXN]; //这里以str1为母串,str2为子串

inline void getNext() {
Next[0] = -1;
int len = strlen(str2);
int j = 0;
int k = -1;

while (j < len) {
if (k == -1 || str2[j] == str2[k]) {
k++;
j++;
Next[j] = k;
} else {
k = Next[k];
}
}
}

inline int kmp() {
int len1 = strlen(str1);
int len2 = strlen(str2);
getNext();

int res = 0;
int j = 0;
for (int i = 0; i < len1; i++) {
while (j && str2[j] != str1[i]) {
j = Next[j];
}
if (str2[j] == str1[i]) {
j++;
}
if (j == len2) {
res++;
j = 0;//字符不能重复使用,初始化模式串位置
}
}
return res;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!