-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
KMP.java
36 lines (31 loc) · 881 Bytes
/
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
class KMP {
static void kmp(String text, String pattern) {
int lenText = text.length();
int lenPattern = pattern.length();
int []b = new int[lenPattern+1];
int i = 0, j = -1;
b[0] = -1;
while(i < lenPattern) {
while(j >= 0 && pattern.charAt(i) != pattern.charAt(j)) j = b[j];
i++;
j++;
b[i] = j;
}
i = 0;
j = 0;
while(i < lenText) {
while(j >= 0 && text.charAt(i) != pattern.charAt(j)) {
j = b[j];
}
i++;
j++;
if (j == lenPattern) {
System.out.println("Pattern is found at index " + (i-j));
j = b[j];
}
}
}
public static void main(String[] args) {
kmp("ABABDABACDABABCABAB", "ABABCABAB");
}
}