KMP 匹配算法

好几次遇到关于 KMP 匹配算法的使用,但是每次看到以后都忘了,所以这里做个记录。

在 B 站看到三哥的 2 个视频,算是讲 KMP 最简单通俗的视频了:

  1. KMP 算法原理和流程
  2. 如何创建 next 数组 (前缀)

代码:

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
43
44
45
46
47
48
49
class Solution {
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null || haystack.length() < needle.length()) {
return -1;
}

if ((haystack.length() == 0 && needle.length() == 0) || (haystack.length() > 0 && needle.length() == 0)) {
return 0;
}

// KMP的核心,先创建next数组
int[] next = genNext(needle);

for (int i = 0, j = 0; i < haystack.length(); i++) {
while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
j = next[j - 1];
}

if (haystack.charAt(i) == needle.charAt(j)) {
j++;
}

if (j == needle.length()) {
return i - (j - 1);
}
}
return -1;
}

private int[] genNext(String needle) {
int[] next = new int[needle.length()];
if (needle.length() == 0) {
return next;
}
next[0] = 0;

for (int i = 1, j = 0; i < needle.length(); i++) {
while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
j = next[j - 1];
}

if(needle.charAt(i) == needle.charAt(j)) {
j++;
}
next[i] = j;
}
return next;
}
}