子串查找

Substring search 也是一个相当 fundamental 的字符串问题。用一句话就可以概括:

Goal. Find pattern of length MM in a text of length NN. (typically N>>MN>>M)

Brute-force substring search. Check for pattern starting at each text position.

java
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
}

暴力做法的最坏时间复杂度是 ∼MN\sim MN 的。另外,由于每次失配时 text pointer 将会回滚 (backup),使得该做法无法适应文本的流式输入 (text string);我们需要更加优秀的 substring search 算法。

未见其人,先闻其声

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] 存储了状态 jj 在读取字符 cc 后转移到的状态 kk。

Match transition.

  • Descriptive. If first jj characters of pattern have already been matched and next char also matches, then first j+1j+1 characters of pattern will be matched.
  • Operative. If in state jj and next char c=pat[j]c = \mathtt{pat}[j], go to state j+1j+1.

Mismatch transition. (!) If in state jj and next char c≠pat[j]c \neq \mathtt{pat}[j], then the last j−1j-1 characters of input are pat[1...j−1]\mathtt{pat}[1...j-1], followed by cc.

根据 KMP 自动机的定义,在字符 c 被读入后,我们将转移到一个状态 kk,在该状态中 pat[0...j−1]+c\mathtt{pat}[0...j-1]+c 的某个长度为 kk 的后缀将与 pat[0...k−1]\mathtt{pat}[0...k-1] (pattern 长度为 kk 的前缀) 匹配。

在第一种情况 (match transition) 下,显然 k=j+1k = j+1。想要找到失配情况下的 kk 则比较 tricky。

我们不妨这样解读 KMP 自动机:对于输入的字符串 ss 与某个 pattern,KMP 自动机将会把 ss 的所有后缀与 pattern 进行匹配,并且返回匹配长度最长的后缀,该后缀的长度为 kk。

能够证明的是,字符串 s1=pat[0...j−1]+cs_1=\mathtt{pat}[0...j-1]+c 与 s2=pat[1...j−1]+cs_2=\mathtt{pat}[1...j-1]+c 输入 KMP 自动机后得到的结果后缀是相同的。s1s_1 除了比 s2s_2 多出了一个后缀以外完全相同,而这个多出来的后缀 pat[0...j−1]+c\mathtt{pat}[0...j-1]+c 不可能是 KMP 自动机返回的结果:这正是由失配 (mismatch transition) 的条件决定的。

To compute dfa[c][j]: Simulate pat[1...j−1]\mathtt{pat}[1...j-1] on DFA and take trancision cc.

  • plain simulation: takes linear time.
  • maintain pat[1...j−1]\mathtt{pat}[1...j-1] as restart state XX: takes only constant time.

remember to update state X each time

java
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 M+NM+N chars to search for a pattern of length MM in a text of length NN.

从有限状态自动机的角度来理解 KMP 对我来说确实是一个全新的视角:但是构造 KMP 自动机的时空代价是 ∼RM\sim RM,这比我之前学习的构造 fail 指针 (标记最长公共前后缀) 的 KMP 算法多了一个小常数 RR。

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 MM text chars when finding one not in the pattern.

问题在于 how much to skip。

我们定义 ii 为定位指针,它所指向的 text 中的字符总是与 pattern 的首字符对齐;定义 cc 为当前的失配字符 (mismatch character)。具体的例子见 slides 53-SubstringSearch。

  • Case 1 - cc not in pattern. increment ii one character beyond the mismatch character.
  • Case 2 - cc in pattern.
    • Case 2a - align the text cc with rightmost pattern cc.
    • Case 2b (heuristic no help since backup will happen) - increment ii by 1.

Property. Substring search with the Boyer-Moore mismatched character heuristic takes about ∼N/M\sim N/M character (sublinear) compares to search for a pattern of length MM in a text of length NN.

虽然 BM 算法的平均时间复杂度十分优秀,但其最坏时间复杂度仍然是 ∼MN\sim MN。但通过向其中添加 KMP-like rule 形成的 BM variant 可以保证最坏 ∼3N\sim 3N 的时间复杂度。

java
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
}

在 Brute-force 的基础上,RK 算法使用 modular hash 进行快速的字符串比较从而大大改善了时间复杂度。

  • Compute a hash of pattern characters 00 to M−1M-1.
  • For each ii, compuate a hash xix_i of text characters ii to M+i−1M+i-1. (Horner's method)
  • If pattern hash = text string hash, check for a match.
  • We can update hash function in constant time: xi+1=(xi−tiRM−1)R+ti+Mx_{i+1}=(x_i-t_iR^{M-1})R+t_{i+M}.

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 MNMN (backup).

In practice, we choose QQ to be a large prime (but not so large to cause overflow). Under reasonable assumptions, probability of a collision is about 1/Q1/Q.

java
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;
    }
}
CC BY-NC-SA 4.0
正在加载评论…