The function had cryptic variable names. Now it's more readable.

This commit is contained in:
_0 2018-10-15 11:52:08 +03:00
parent c6e6610909
commit 1177b54746

View File

@ -1,25 +1,26 @@
/* /*
Implementation of KnuthMorrisPratt algorithm Implementation of KnuthMorrisPratt algorithm
Usage: Usage: see the main function for an example
final String T = "AAAAABAAABA";
final String P = "AAAA";
KMPmatcher(T, P);
*/ */
public class KMP { public class KMP {
//a working example
// find the starting index in string T[] that matches the search word P[] public static void main(String[] args) {
public void KMPmatcher(final String T, final String P) { final String haystack = "AAAAABAAABA"; //This is the full string
final int m = T.length(); final String needle = "AAAA"; //This is the substring that we want to find
final int n = P.length(); KMPmatcher(haystack, needle);
final int[] pi = computePrefixFunction(P); }
// find the starting index in string haystack[] that matches the search word P[]
public static void KMPmatcher(final String haystack, final String needle) {
final int m = haystack.length();
final int n = needle.length();
final int[] pi = computePrefixFunction(needle);
int q = 0; int q = 0;
for (int i = 0; i < m; i++) { for (int i = 0; i < m; i++) {
while (q > 0 && T.charAt(i) != P.charAt(q)) { while (q > 0 && haystack.charAt(i) != needle.charAt(q)) {
q = pi[q - 1]; q = pi[q - 1];
} }
if (T.charAt(i) == P.charAt(q)) { if (haystack.charAt(i) == needle.charAt(q)) {
q++; q++;
} }
@ -28,11 +29,9 @@ public class KMP {
q = pi[q - 1]; q = pi[q - 1];
} }
} }
} }
// return the prefix function // return the prefix function
private int[] computePrefixFunction(final String P) { private static int[] computePrefixFunction(final String P) {
final int n = P.length(); final int n = P.length();
final int[] pi = new int[n]; final int[] pi = new int[n];
pi[0] = 0; pi[0] = 0;
@ -49,7 +48,6 @@ public class KMP {
pi[i] = q; pi[i] = q;
} }
return pi; return pi;
} }
} }