- Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathKMP.java
More file actions
Latest commit
53 lines (47 loc) · 1.16 KB
/
Copy pathKMP.java
File metadata and controls
53 lines (47 loc) · 1.16 KB
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
/**
*
*/
publicclassKMP {
/**
* https://www.jianshu.com/p/e2bd1ee482c3
*/
publicstaticintfind(Stringtxt, Stringpat, int[] next) {
intM = txt.length();
intN = pat.length();
inti = 0;
intj = 0;
while (i < M && j < N) {
if (j == -1 || txt.charAt(i) == pat.charAt(j)) {
i++;
j++;
} else {
j = next[j];
}
if (j == N) returni - j;
}
return -1;
}
publicstaticint[] getNext(Stringpat) {
intN = pat.length();
int[] next = newint[N];
next[0] = -1;
intk = -1;
intj = 0;
while (j < N - 1) {
if (k == -1 || pat.charAt(j) == pat.charAt(k)) {
k++;
j++;
next[j] = k;
} else {
k = next[k];
}
}
returnnext;
}
publicstaticvoidmain(String[] args) {
Stringtxt = "BBC ABCDAB CDABABCDABCDABDE";
Stringpat = "ABCDABD";
int[] next = getNext(pat);
System.out.println(find(txt, pat, next));
}
}