Skip to content

Commit 1177b54

Browse files
_0_0
authored andcommitted
The function had cryptic variable names. Now it's more readable.
1 parent c6e6610 commit 1177b54

1 file changed

Lines changed: 16 additions & 18 deletions

File tree

Others/KMP.java

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,26 @@
1-
21
/*
32
Implementation of Knuth–Morris–Pratt algorithm
4-
Usage:
5-
final String T = "AAAAABAAABA";
6-
final String P = "AAAA";
7-
KMPmatcher(T, P);
3+
Usage: see the main function for an example
84
*/
95
public class KMP {
10-
11-
// find the starting index in string T[] that matches the search word P[]
12-
public void KMPmatcher(final String T, final String P) {
13-
final int m = T.length();
14-
final int n = P.length();
15-
final int[] pi = computePrefixFunction(P);
6+
//a working example
7+
public static void main(String[] args) {
8+
final String haystack = "AAAAABAAABA"; //This is the full string
9+
final String needle = "AAAA"; //This is the substring that we want to find
10+
KMPmatcher(haystack, needle);
11+
}
12+
// find the starting index in string haystack[] that matches the search word P[]
13+
public static void KMPmatcher(final String haystack, final String needle) {
14+
final int m = haystack.length();
15+
final int n = needle.length();
16+
final int[] pi = computePrefixFunction(needle);
1617
int q = 0;
1718
for (int i = 0; i < m; i++) {
18-
while (q > 0 && T.charAt(i) != P.charAt(q)) {
19+
while (q > 0 && haystack.charAt(i) != needle.charAt(q)) {
1920
q = pi[q - 1];
2021
}
2122

22-
if (T.charAt(i) == P.charAt(q)) {
23+
if (haystack.charAt(i) == needle.charAt(q)) {
2324
q++;
2425
}
2526

@@ -28,11 +29,9 @@ public void KMPmatcher(final String T, final String P) {
2829
q = pi[q - 1];
2930
}
3031
}
31-
3232
}
33-
3433
// return the prefix function
35-
private int[] computePrefixFunction(final String P) {
34+
private static int[] computePrefixFunction(final String P) {
3635
final int n = P.length();
3736
final int[] pi = new int[n];
3837
pi[0] = 0;
@@ -49,7 +48,6 @@ private int[] computePrefixFunction(final String P) {
4948
pi[i] = q;
5049

5150
}
52-
5351
return pi;
5452
}
55-
}
53+
}

0 commit comments

Comments
 (0)