单词查找树

Tries

String symbol table. Symbol table specialized to string keys. It avoids examing the entrie key (as with string sorting) thus perform better than traditional symbol tables with string keys.

用红黑树或 linear-probing hashing 实现的 string symbol tables 已经拥有较为优秀的效率;但一个更为 ingenious 的,string-specialized 的数据结构是 tries(字典树)。

R-way Tries

Tries 的名字来源于 retrieval,但读作 try。相当简单优雅的数据结构,就不详细介绍了。

  • Search hit. Need to examine all LL characters for equality.
  • Search miss. (typical case) examine only a few characters (sublinear).
  • Space. RR null links at each leaf.

Bottom line. Fast search hit and even faster search miss, but wasted space.

trie 的删除操作也十分简单:

  • Find the node corresponding to key and set value to null.
  • If node has null value and all null links, remove that node (and recur).
java
// This is a Trie Symbol Table, which associate a value with each string key. 
// To create a Trie plainly storing strings, use Trie Set.

public class TrieST<Value> {
    private static final int R = 256;
    private Node root = new Node();
    
    private static class Node {
        // use Object instead of Value since no generic array creation in Java
        private Object value;
        private Node[] next = new Node[R];
    }
    
    public void put(String key, Value val) {
        root = put(root, key, value, 0);
    }
    
    private Node put(Node x, String key, Value val, int d) {
        if (x == null) x = new Node();
        if (d == key.length()) {
            x.val = val;
            return x;
        }
        char c = key.charAt(d);
        x.next[c] = put(x.next[c], key, val, d+1);
        return x;
    }
    
    public boolean contains(String key) {
        return get(key) != null;
    }
    
    public Value get(String key) {
        Node x = get(root, key, 0);
        if (x == null)	return null;
        return (Value) x.val;    // cast needed
    }
    
    private Node get(Node x, String key, int d) {
        if (x == null)	return null;
        if (d == key.length())	return x;
        char c = key.charAt(d);
        return get(x.next[c], key, d+1);
    }
}

Ternary Search Tries

又是 Sedgewick 教授发明的算法之一(Bentley & Sedgewick),ORZ。

  • Store characters and values in nodes (not keys).
  • Each node has 3 children: smaller (left), equal (middle), larger (right).
  • Search or Insert.
    • If less, take left link; If greater, take right link.
    • If equal, take the middle link and move to the next key character.

TST is as fast as hashing (for string keys), space efficient.

TSTs 改善了传统 R-way tries 耗费空间过多的缺点(从 (R+1)N(R+1)N 优化至 4N4N),同时仍然维持了 tries 优秀的时间效率(从 LL 到可以接受的 L+ln⁡NL+\ln{N})。

TSTs 还存在许多 variants:balanced TSTs via rotations(can achieve worst-case L+log⁡NL+\log{N} guarantees)与 TSTs with R2R^2 branching(对特定的输入进一步提升时空效率)。

总而言之,TST 是这样的一种数据结构,它:

  • Faster than hashing (especially for search misses).
  • More space-efficient than R-way tries.
  • More flexible than red-black BSTs.
java
public class TST<Value> {
    private Node root;
    
    private class Node {
        private Value val;
        private char c;
        private Node left, mid, right;
    }
    
    public void put(String key, Value val) {
        root = put(root, key, val, 0);
    }
    
    private Node put(Node x, String key, Value val, int d) {
        char c = key.charAt(d);
        if (x == null)	{ x = new Node(); x.c = c; }
        if      (c < x.c)               x.left  = put(x.left,  key, val, d);
        else if (c > x.c)               x.right = put(x.right, key, val, d);
        else if (d < key.length() - 1)  x.mid   = put(x.mid,   key, val, d+1);
        else                            x.val = val;
        return x;
    }
    
    public boolean contains(String key) {
        return get(key) != null; 
    }
    
    public Value get(String key) {
        Node x = get(root, key, 0);
        if (x == null)	return null;
        return x.val;
    }
    
    private Node get(Node x, String key, int d) {
        if (x == null)	return null;
        char c = key.charAt(d);
        if      (c < x.c)               return get(x.left,  key, d);
        else if (c > x.c)               return get(x.right, key, d);
        else if (d < key.length() - 1)  return get(x.mid,   key, d+1);
        else                            return x;
    }
}

Character-Based Operations

以 string 作为键值的 string symbol table implemented with tries 不仅仅支持以 string 为基本单位的操作,更支持基于字符的操作(character-based operations)。

  • Ordered iteration(引入了利用 trie 进行 string sorting 的新思路).
    • Do inorder traversal of trie; add keys encountered to a queue.
    • Maintain a sequence of characters on path from root to node.
  • Prefix matches. Find all keys in a symbol table starting with a given prefix.
  • Longest prefix. Find longest key in symbol table that is a prefix of query string.
  • T9 texting.
    • Multi-tap input. 不断按某键直到切换到想要的字母。
    • T9 text input. Find all words that correspond to given sequence of numbers.
  • Patricia trie (crit-bit tree, radix tree). 将 trie 上的 internal one-way branching(象征着多个字符串的共同前缀)压缩成一个节点,提升了 trie 的空间利用率。
  • Suffix tree. Patricia trie of suffixes of a string; can be constructed in linear time.

最后,我们再来对 string symbol table 的不同实现进行一个全面的比较与总结:

Implementation Performance Guarantee Features
Red-black BST. log⁡N\log{N} key (string) compares. Supports ordered symbol table API.
Hash tables. constant number of probes. Requires good hash function for key type.
R-way tries or TSTs. log⁡N\log{N} characters accessed. Supports character-based operations.
CC BY-NC-SA 4.0
正在加载评论…