KMP算法

题目

AcWing 831

代码

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
#include<bits/stdc++.h>

using namespace std;

const int N = 100010, M = 1000010;

int n, m;
char p[N], s[M];
int Next[N];

int main() {
cin >> n >> p + 1 >> m >> s + 1;

//求解Next[i]过程
for (int i = 2, j = 0; i <= n; i++) {
while (j && p[i] != p[j + 1]) j = Next[j];
if (p[i] == p[j + 1]) j++;
Next[i] = j;
}

//kmp匹配过程
for (int i = 1, j = 0; i <= m; i++) {
while (j && s[i] != p[j + 1]) j = Next[j];
if (s[i] == p[j + 1]) j++;
if (j == n) {
printf("%d ", i - n); /* 本题下标从0开始,与上文不同 */
j = Next[j];
}
}
return 0;
}

参考

  1. AcWing 831详解
  2. KMP算法图解(无代码)