Skip to content

Commit

Permalink
The function had cryptic variable names. Now it's more readable.
Browse files Browse the repository at this point in the history
  • Loading branch information
_0 authored and _0 committed Oct 15, 2018
1 parent c6e6610 commit 1177b54
Showing 1 changed file with 16 additions and 18 deletions.
34 changes: 16 additions & 18 deletions Others/KMP.java
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@

/*
Implementation of Knuth–Morris–Pratt algorithm
Usage:
final String T = "AAAAABAAABA";
final String P = "AAAA";
KMPmatcher(T, P);
Usage: see the main function for an example
*/
public class KMP {

// find the starting index in string T[] that matches the search word P[]
public void KMPmatcher(final String T, final String P) {
final int m = T.length();
final int n = P.length();
final int[] pi = computePrefixFunction(P);
//a working example
public static void main(String[] args) {
final String haystack = "AAAAABAAABA"; //This is the full string
final String needle = "AAAA"; //This is the substring that we want to find
KMPmatcher(haystack, needle);
}
// 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;
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];
}

if (T.charAt(i) == P.charAt(q)) {
if (haystack.charAt(i) == needle.charAt(q)) {
q++;
}

Expand All @@ -28,11 +29,9 @@ public void KMPmatcher(final String T, final String P) {
q = pi[q - 1];
}
}

}

// return the prefix function
private int[] computePrefixFunction(final String P) {
private static int[] computePrefixFunction(final String P) {
final int n = P.length();
final int[] pi = new int[n];
pi[0] = 0;
Expand All @@ -49,7 +48,6 @@ private int[] computePrefixFunction(final String P) {
pi[i] = q;

}

return pi;
}
}
}

0 comments on commit 1177b54

Please sign in to comment.