1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
public int kmpSearch(String text, String pattern) { int i = 0; int j = 0;
int textLen = text.length(); int patternLen = pattern.length();
int[] next = new int[patternLen];
buildNext(pattern, next);
while (i < textLen && j < patternLen) { if (j == -1 || text.charAt(i) == pattern.charAt(j)) { i++; j++; } else { j = next[j]; } } if (j == patternLen) return i - j; else return -1; }
private void buildNext(String pattern, int[] next) { int patternLen = pattern.length(); next[0] = -1; int k = -1; int j = 0; while (j < patternLen - 1) { if (k == -1 || pattern.charAt(j) == pattern.charAt(k)) { ++j; ++k; if (pattern.charAt(j) != pattern.charAt(k)) next[j] = k; else next[j] = next[k]; } else { k = next[k]; } } }
|