我指的是“Sedgewick & Wyane 的算法第四版”字符串匹配第 5 章。
给定的算法是 KMP 子字符串搜索,它从模式状态构建 DFA。我了解构建 DFA 的算法,代码如下:
public KMP(String pat) {
this.R = 256;
this.pat = pat;
// build DFA from pattern
int m = pat.length();
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.
}
}
我无法得到以下行: x = dfa[pat.charAt(j)][x]; // Update restart state.
我知道这个值是通过在部分构建 DFA 中提供 pat[1..j-1] 来实现的,但无法获得该代码,它是如何实现这一点的。
我也明白 x 是模式的最长前缀的长度也是后缀。
我见过许多其他相关问题,但这些问题与理解算法本身有关。
我需要了解如何x = dfa[pat.charAt(j)][x]; // Update restart state.
模拟重启状态。