子串查找
Substring Search
Substring search 也是一个相当 fundamental 的字符串问题。用一句话就可以概括:
Goal. Find pattern of length
Brute-force substring search. Check for pattern starting at each text position.
public static int search(String pat, String txt) {
int M = pat.length();
int N = txt.length();
for (int i = 0; i <= N-M; ++i) {
int j;
for (j = 0; j < M; ++j)
if (txt.charAt(i+j) != pat.charAt(j))
break;
if (j == M) return i;
}
return N; // not found
}
暴力做法的最坏时间复杂度是
Knuth-Morris-Pratt
很早以前就学过并被惊艳过的 KMP 算法;今天以另外的角度来学习这个算法,倍感新鲜。
首先来介绍一下 DFA (deterministic finite state automaton, 有限状态自动机)。
- Finate number of states (including start and halt).
- Exactly one transition for each char in alphabet.
- Accept if sequence of transitions leads to halt state.
上图是 pattern ABABAC 构建的 KMP 自动机;其接受且仅接受以该 pattern 为后缀的字符串。将给出的 text stream 输入该 DFA,若在某个时刻能够到达 halting state,说明匹配成功。
这是因为 text stream 在该时刻形成的前缀被 KMP 自动机接受了;根据 KMP 自动机的性质,这一前缀一定存在某个 ABABAC 的后缀。而字符串前缀的后缀一定是该字符串的子串:据此我们成功将 substring search 问题转化为了基于 pattern 的 KMP 自动机构建问题。
KMP 自动机的 internal representation 是一个二维数组 dfa[][]: dfa[c][j] 存储了状态
Match transition.
- Descriptive. If first
characters of pattern have already been matched and next char also matches, then first characters of pattern will be matched. - Operative. If in state
and next char , go to state .
Mismatch transition. (!) If in state
根据 KMP 自动机的定义,在字符 c 被读入后,我们将转移到一个状态
在第一种情况 (match transition) 下,显然
我们不妨这样解读 KMP 自动机:对于输入的字符串
能够证明的是,字符串
To compute dfa[c][j]: Simulate
- plain simulation: takes linear time.
- maintain
as restart state : takes only constant time.
public KMP(String pat) {
this.pat = pat;
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 transitions
dfa[pat.charAt(j)][j] = j+1; // set match transition
X = dfa[pat.charAt(j)][X]; // update restart state
}
}
Proposition. KMP substring search accesses no more than
从有限状态自动机的角度来理解 KMP 对我来说确实是一个全新的视角:但是构造 KMP 自动机的时空代价是
Boyer-Moore
Boyer-Moore 是一种启发式的字符串匹配算法,其包含两种规则:坏字符启发 (bad character heuristic) 与好后缀启发 (good suffix heuristic). BM 算法的 intuition 在于:
- Scan characters in pattern from right to left.
- Can skip as many as
text chars when finding one not in the pattern.
问题在于 how much to skip。
我们定义
- Case 1 -
not in pattern. increment one character beyond the mismatch character. - Case 2 -
in pattern. - Case 2a - align the text
with rightmost pattern . - Case 2b (heuristic no help since backup will happen) - increment
by 1.
- Case 2a - align the text
Property. Substring search with the Boyer-Moore mismatched character heuristic takes about
虽然 BM 算法的平均时间复杂度十分优秀,但其最坏时间复杂度仍然是
public int BMsearch(String text) {
int N = txt.length();
int M = pat.length();
int skip;
for (int i = 0; i <= N-M; i += skip) {
skip = 0;
for (int j = M-1; j >= 0; --j) {
if (pat.charAt(j) != txt.charAt(i+j)) {
skip = Math.max(1, j - rightmost[txt.charAt(i+j)]); // precompute rightmost
break;
}
}
if (skip == 0) return i; // match
}
return N; // not match
}
Rabin-Karp Fingerprint Search
在 Brute-force 的基础上,RK 算法使用 modular hash 进行快速的字符串比较从而大大改善了时间复杂度。
- Compute a hash of pattern characters
to . - For each
, compuate a hash of text characters to . (Horner's method) - If pattern hash = text string hash, check for a match.
- We can update hash function in constant time:
.
Rabin-Karp 算法有两种实现的方式:
- Monte Carlo version - return match if hash match: linear-time guarantee but not always return the correct answer.
- Las Vegas version - always returns correct answer: worst-case running time is
(backup).
In practice, we choose
public class RabinKarp {
private long patHash; // pattern hash value
private int M; // pattern length
private long Q; // modulus
private int R; // radix
private long RM; // R^(M-1) % Q
public RabinKarp(String pat) {
M = pat.length();
R = 256;
Q = longRandomPrime();
RM = 1;
for (int i = 1; i <= M-1; ++i)
RM = (R * RM) % Q;
patHash = hash(pat, M);
}
private long hash(String key, int M) {
long h = 0;
for (int j = 0; j < M; ++j)
h = (R * h + key.charAt(j)) % Q;
return h;
}
public int search(String txt) { // Monte Carlo Version
int N = txt.length();
int txtHash = hash(txt, M);
if (patHash == txtHash) return 0;
for (int i = M; i < N; ++i) {
txtHash = (txtHash + Q - RM*txt.charAt(i-M) % Q) % Q;
txtHash = (txtHash*R + txt.charAt(i)) % Q;
if (patHash == txtHash) return i - M + 1;
}
return N;
}
}


