m = P.length for q = 0 to m for each charater a ∈ Σ k = min(m+1,q+2) repeat k = k - 1 until P[0:k]==(P[q]+a)[q+1-k:q+1] //P[0:k]=P[q]+a后缀(P[q]+a)[q+1-k:q+1] δ(q,a) = k return δ
staticintgetNextState(char[] pat, int m, int state, int x){
// 如果当前字符与模式中下一个字符相同,则直接+1 if (state < m && x == pat[state]) { return state + 1; }
// ns是下一个状态 int ns, i; // 倒序遍历状态 for (ns = state; ns > 0; ns--) { // 如果模式中包含这个字符,ns-1是符号下标 if (pat[ns - 1] == x) { // 遍历前缀所有字符 for (i = 0; i < ns - 1; i++) { // 比较 pat[0..i] 前缀,pat[0..state-1]c 后缀 // ns-1是c的位置,i为前缀,state-(ns-1)-i为后缀 if (pat[i] != pat[state - ns + 1 + i]) { break; } } // 前缀=后缀 if (i == ns - 1) { return ns; } } }
return0; }
staticvoidcomputeTransFun(char[] pat, int m, int[][] tf){ int state, x; for (state = 0; state <= m; ++state) { for (x = 0; x < NO_OF_CHARS; ++x) { tf[state][x] = getNextState(pat, m, state, x); } } }
staticvoidsearch(char[] pat, char[] txt){ int m = pat.length; int n = txt.length;
int[][] tf = newint[m + 1][NO_OF_CHARS];
// 构建转换函数 computeTransFun(pat, m, tf);
int i, state = 0; for (i = 0; i < n; i++) { state = tf[state][txt[i]]; if (state == m) { System.out.println("Pattern found at index " + (i - m + 1)); } } }