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
| class Solution { public int strStr(String haystack, String needle) { int n = haystack.length(); int m = needle.length(); if (m == 0) return 0;
int[] next = buildNext(needle);
int i = 0; int j = 0;
while (i < n) { if (j == -1 || haystack.charAt(i) == needle.charAt(j)) { i++; j++; } else { j = next[j]; }
if (j == m) return i - j; }
return -1; }
private int[] buildNext(String pattern) { int m = pattern.length(); int[] next = new int[m]; next[0] = -1;
int j = 0; int k = -1;
while (j < m - 1) { if (k == -1 || pattern.charAt(j) == pattern.charAt(k)) { j++; k++; next[j] = k; } else { k = next[k]; } }
return next; } }
|