Skip to content

Instantly share code, notes, and snippets.

@kehtolaulu
Created May 19, 2018 17:47
Show Gist options
  • Select an option

  • Save kehtolaulu/204b6b24089537766fe8668590931ee0 to your computer and use it in GitHub Desktop.

Select an option

Save kehtolaulu/204b6b24089537766fe8668590931ee0 to your computer and use it in GitHub Desktop.
Knuth-Morris-Pratt algorithm
public class KMP {
public static void main(String[] args) {
String string = "abcdefgabd";
String word = "defg";
System.out.println(getFirstEntry(string, word));
}
public static int[] prefixFunction(String s) {
int[] p = new int[s.length()];
int k = 0;
for (int i = 1; i < s.length(); i++) {
while (k > 0 && s.charAt(k) != s.charAt(i))
k = p[k - 1];
if (s.charAt(k) == s.charAt(i))
++k;
p[i] = k;
}
return p;
}
public static int getFirstEntry(String s, String pattern) {
int m = pattern.length();
if (m == 0)
return 0;
int[] p = prefixFunction(pattern);
for (int i = 0, k = 0; i < s.length(); i++)
while (true) {
if (pattern.charAt(k) == s.charAt(i)) {
k++;
if (k == m) {
return i + 1 - m;
}
break;
}
if (k == 0) {
break;
}
k = p[k - 1];
}
return -1;
}
}
@Alexey1994
Copy link

Alexey1994 commented Jul 8, 2018

while (true) -> for(;;)

@Alexey1994
Copy link

public static int[] prefixFunction(String s) -> private static int[] prefixFunction(String s)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment