【算法4】5.2.单词查找树

单词查找树

单词查找树适用于以字符串为键的查找算法。

性能:

  • 查找命中所需的时间与被查找的键的长度成正比
  • 查找未命中只需检查若干个字符

以字符串为键的符号表的 API:

public interface StringST<Value> {
    void put(String key, Value val); // 键为 null 表示删除键
    Value get(String key);
    void delete(String key);
    boolean isEmpty();
    String longestPrefixOf(String s); // 返回一个最长的键,该键是 s 的前缀
    Iterable<String> keysWithPrefix(String s); // 返回以 s 为前缀的所有键
    Iterable<String> keysThatMatch(String s); // 返回所有匹配的键,字符 . 表示任意字符
    int size();
    Iterable<String> keys();
}

单词查找树由结点组成。
每个结点含有 R 条链接和一个可选的值。(R 是字符集大小,这种单词查找树也叫 R 向单词查找树)
一个结点通常会含有大量的空链接,在绘制单词查找树时会忽略这些空链接。

在单词查找树中,值保存在键对应的尾结点中。

private static class Node {
    Object val; // 节点保存的值
    Node[] next = new Node[R]; // 指向子节点的指针
}

单词查找树实现:

public class Trie <Value>{
    private static final int R = 128; // ASCII 字符集大小
    private Node root;

    private static class Node {
        Object val; // 节点保存的值
        Node[] next = new Node[R]; // 指向子节点的指针
    }

    public void put(String key, Value val) {
        root = put(key, val, root, 0, key.length());
    }

    private Node put(String key, Value val, Node node, int cur, int len) {
        if (node == null) {
            node = new Node();
        }
        if (cur == len) {
            node.val = val;
        } else {
            char c = key.charAt(cur);
            node.next[c] = put(key, val, node.next[c], cur + 1, len);
        }
        return node;
    }

    public Value get(String key) {
        Node node = get(key, root, 0, key.length());
        if (node == null) {
            return null;
        }
        return (Value) node.val;
    }

    private Node get(String key, Node node, int cur, int len) {
        if (node == null) {
            return null;
        }
        if (cur == len) {
            return node;
        }
        return get(key, node.next[key.charAt(cur)], cur + 1, len);
    }
}
posted @ 2022-06-04 18:07  廖子博  阅读(53)  评论(0)    收藏  举报