-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKmpPatternSearching.java
More file actions
41 lines (34 loc) · 979 Bytes
/
KmpPatternSearching.java
File metadata and controls
41 lines (34 loc) · 979 Bytes
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
/**
* KMP Pattern Searching
* Also known as Knuth-Morris-Pratt algorithm
*/
public class KmpPatternSearching {
public static void main(String[] args) {
String text = "AABAACAADAABAABA";
String pattern = "AABA";
int[] lps = ComputeLpsArray.computeLpsArray(pattern);
KmpSearch(text, pattern, lps);
}
public static void KmpSearch(String text, String pattern, int[] lps) {
int i = 0;
int j = 0;
int n = text.length();
int m = pattern.length();
while (i < n) {
if (text.charAt(i) == pattern.charAt(j)) {
i++;
j++;
} else {
if (j == 0) {
i++;
} else {
j = lps[j - 1];
}
}
if (j == m) {
System.out.println("Pattern found at index " + (i - j));
j = lps[j - 1];
}
}
}
}