Created
May 19, 2018 17:47
-
-
Save kehtolaulu/204b6b24089537766fe8668590931ee0 to your computer and use it in GitHub Desktop.
Knuth-Morris-Pratt algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } | |
| } | |
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
while (true) -> for(;;)