Last active
March 10, 2017 10:32
-
-
Save ok3141/8b9843c7410205539355ff3e42de0f1d to your computer and use it in GitHub Desktop.
KMP substring search 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 int indexOf(String t, String p) { | |
| return compile(p).matcher(t).find(); | |
| } | |
| public static Pattern compile(String p) { | |
| return new Pattern(p); | |
| } | |
| public static class Pattern { | |
| protected final String p; | |
| protected final int[] d; | |
| public Pattern(String p) { | |
| this.p = p; | |
| int m = p.length(); | |
| d = new int[m]; | |
| int i = 1; | |
| int j = 0; | |
| while (i < m) { | |
| if (p.charAt(i) == p.charAt(j)) { | |
| d[i] = j + 1; | |
| i += 1; | |
| j += 1; | |
| } else { | |
| if (j > 0) { | |
| j = d[j - 1]; | |
| } else { | |
| i += 1; | |
| } | |
| } | |
| } | |
| } | |
| public Matcher matcher(String t) { | |
| return new Matcher(t, p, d); | |
| } | |
| } | |
| public static class Matcher { | |
| protected final String t; | |
| protected final String p; | |
| protected final int[] d; | |
| protected int i; | |
| protected int j; | |
| public Matcher(String t, String p, int[] d) { | |
| this.t = t; | |
| this.p = p; | |
| this.d = d; | |
| } | |
| public int find() { | |
| int n = t.length(); | |
| int m = p.length(); | |
| while (i < n) { | |
| if (t.charAt(i) == p.charAt(j)) { | |
| i += 1; | |
| j += 1; | |
| if (j == m) { | |
| int r = i - j; | |
| j = 0; | |
| return r; | |
| } | |
| } else { | |
| if (j > 0) { | |
| j = d[j - 1]; | |
| } else { | |
| i += 1; | |
| } | |
| } | |
| } | |
| return -1; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment