-
Notifications
You must be signed in to change notification settings - Fork 92
/
KMP.java
53 lines (47 loc) · 1.16 KB
/
KMP.java
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
50
51
52
53
/**
*
*/
public class KMP {
/**
* https://www.jianshu.com/p/e2bd1ee482c3
*/
public static int find(String txt, String pat, int[] next) {
int M = txt.length();
int N = pat.length();
int i = 0;
int j = 0;
while (i < M && j < N) {
if (j == -1 || txt.charAt(i) == pat.charAt(j)) {
i++;
j++;
} else {
j = next[j];
}
if (j == N) return i - j;
}
return -1;
}
public static int[] getNext(String pat) {
int N = pat.length();
int[] next = new int[N];
next[0] = -1;
int k = -1;
int j = 0;
while (j < N - 1) {
if (k == -1 || pat.charAt(j) == pat.charAt(k)) {
k++;
j++;
next[j] = k;
} else {
k = next[k];
}
}
return next;
}
public static void main(String[] args) {
String txt = "BBC ABCDAB CDABABCDABCDABDE";
String pat = "ABCDABD";
int[] next = getNext(pat);
System.out.println(find(txt, pat, next));
}
}