关于Trie树

180 阅读1分钟

字典树和并查集

回顾:

  • BFS and DFS
  • Binary Search Tree

字典树

you -> youtube

搜索引擎,应运而生 前缀 感应整个单词

字典树,又称Tire 树,单词查找树/键树,树形结构。典型应用于:统计和排序大量字符串,但不限于字符串,所以经常被搜索引擎系统用于文本词频统计。

优点:最大限度减少无谓的字符串比较,查询效率高于哈希表

208. 实现 Trie (前缀树)

public class TrieNode {
  public TrieNode[] children = new TrieNode[26];
  public boolean isWord;
  public TrieNode() {}
}
​
public class Trie {
​
  private TrieNode root;
​
  public Trie() {
    root = new TrieNode();
  }
​
  public void insert(String word) {
    TrieNode node = root;
    for (int i = 0; i < word.length(); i++) {
      char c = word.charAt(i);
      if (node.children[c - 'a'] == null) {
        node.children[c - 'a'] = new TrieNode();
      }
      node = node.children[c - 'a'];
    }
    node.isWord = true;
  }
​
  public boolean search(String word) {
    return searchPrefix(word) != null && searchPrefix(word).isWord;
  }
​
  public boolean startWith(String word) {
    return searchPrefix(word) != null;
  }
​
  private TrieNode searchPrefix(String word) {
    TrieNode node = root;
    for (int i = 0; i < word.length(); i++) {
      char c = word.charAt(i);
      if (node.children[c - 'a'] == null) {
        return null;
      }
      node = node.children[c - 'a'];
    }
    return node;
  }
​
}
​

\