Skip to content

add KMP algorithm; improve binary search #124

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 2, 2017
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
KMP algorithm
  • Loading branch information
lvncnt authored Oct 1, 2017
commit 79a73aebb41df045c8aed286171b8051cd886554
55 changes: 55 additions & 0 deletions Misc/KMP.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@

/*
Implementation of Knuth–Morris–Pratt algorithm
Usage:
final String T = "AAAAABAAABA";
final String P = "AAAA";
KMPmatcher(T, P);
*/
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);
int q = 0;
for (int i = 0; i < m; i++) {
while (q > 0 && T.charAt(i) != P.charAt(q)) {
q = pi[q - 1];
}

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

if (q == n) {
System.out.println("Pattern starts: " + (i + 1 - n));
q = pi[q - 1];
}
}

}

// return the prefix function
private int[] computePrefixFunction(final String P) {
final int n = P.length();
final int[] pi = new int[n];
pi[0] = 0;
int q = 0;
for (int i = 1; i < n; i++) {
while (q > 0 && P.charAt(q) != P.charAt(i)) {
q = pi[q - 1];
}

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

pi[i] = q;

}

return pi;
}
}