class Solution {
private int R; // the radix
private int m; // length of pattern
private int[][] dfa; // the KMP automoton
public int strStr(String haystack, String needle) {
KMP(needle);
int value = search(haystack);
if(value == haystack.length()){
return -1;
}
return value;
}
public void KMP(String pat) {
R = 256;
m = pat.length();
// build DFA from pattern
dfa = new int[R][m];
dfa[pat.charAt(0)][0] = 1;
for (int x = 0, j = 1; j < m; j++) {
for (int c = 0; c < R; c++)
dfa[c][j] = dfa[c][x]; // Copy mismatch cases.
dfa[pat.charAt(j)][j] = j+1; // Set match case.
x = dfa[pat.charAt(j)][x]; // Update restart state.
}
}
public int search(String txt) {
// simulate operation of DFA on text
int n = txt.length();
int i, j;
for (i = 0, j = 0; i < n && j < m; i++) {
j = dfa[txt.charAt(i)][j];
}
if (j == m) return i - m; // found
return n; // not found
}
}
参考
算法第四版