算法模式:前缀树

算法模式:前缀树

在上一篇文章 算法模式:深度优先搜索 介绍了介绍一种即适用于树,又适用于图的的算法模式。本篇文章,介绍一种关于特殊的树的算法模式:前缀树。

前缀树

前缀树,又称为字典树,还叫单词查找树,英文是 Trie,也有叫 Prefix Tree。顾名思义,就是一个像字典一样的树。如图:

前缀树
图 1. 前缀树

前缀树是一种有序树,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。一般情况下,不是所有的节点都有对应的值,只有叶子节点和部分内部节点所对应的键才有相关的值。

LeetCode 208. 实现 Trie (前缀树)

Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补全和拼写检查。

请你实现 Trie 类:

  • Trie() 初始化前缀树对象。

  • void insert(String word) 向前缀树中插入字符串 word

  • boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false

  • boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false

示例:

输入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
输出
[null, null, true, false, true, null, true]

解释
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // 返回 True
trie.search("app");     // 返回 False
trie.startsWith("app"); // 返回 True
trie.insert("app");
trie.search("app");     // 返回 True

提示:

  • 1 <= word.length, prefix.length <= 2000

  • wordprefix 仅由小写英文字母组成

  • insertsearchstartsWith 调用次数 总计 不超过 3 * 104

思路分析

所谓前缀树,就是将单词拆分成字符,依次将其“添加”到一棵树上。从根节点到结束节点,一条路径表示一个单词。所以,就是实现字典树,就是构造这样一棵树。代码如下:

/**
 * 没想到竟然一次通过,😁
 *
 * @author D瓜哥 · https://www.diguage.com
 * @since 2025-04-02 19:42:48
 */
class Trie {
  private Map<Character, Node> trie;

  public Trie() {
    trie = new HashMap<>();
  }

  public void insert(String word) {
    Map<Character, Node> curr = trie;
    Node node = null;
    for (int i = 0; i < word.length(); i++) {
      char c = word.charAt(i);
      node = curr.get(c);
      if (node == null) {
        node = new Node(c);
        curr.put(c, node);
      }
      curr = node.children;
    }
    node.isEnd = true;
  }

  public boolean search(String word) {
    Node node = searchPrefix(word);
    return node != null && node.isEnd;
  }

  public boolean startsWith(String prefix) {
    return searchPrefix(prefix) != null;
  }

  private Node searchPrefix(String word) {
    Map<Character, Node> curr = trie;
    Node node = null;
    for (int i = 0; i < word.length(); i++) {
      char c = word.charAt(i);
      node = curr.get(c);
      if (node == null) {
        return null;
      }
      curr = node.children;
    }
    return node;
  }

  private static class Node {
    char data;
    boolean isEnd;
    Map<Character, Node> children = new HashMap<>();

    public Node(char data) {
      this.data = data;
    }
  }
}