Trie 树,也叫字典树,它是一个多叉树。它是一种专门处理字符串匹配的数据结构,用来解决在一组字符串集合中快速查找某个字符串的问题。其本质就是利用字符串之间的公共前缀,将重复的前缀合并在一起。

Trie 可视化:https://www.cs.usfca.edu/~galles/visualization/Trie.html

Trie 的基础知识可以查看 算法与数据结构之美——35 | Trie树:如何实现搜索引擎的搜索关键词提示功能?

  1. class Node {
  2. isWord: boolean;
  3. next: Map<string, Node>;
  4. constructor(isWord = false) {
  5. this.isWord = isWord;
  6. this.next = new Map();
  7. }
  8. }
  9. interface TrieInterface {
  10. root: Node;
  11. size: number;
  12. getSize: () => number;
  13. add: (word: string) => void;
  14. contains: (word: string) => boolean;
  15. }
  16. class Trie implements TrieInterface {
  17. root = new Node();
  18. size = 0;
  19. getSize(): number {
  20. return this.size;
  21. }
  22. /**
  23. * 向 Trie 中添加一个新的单词 word
  24. * @param word
  25. */
  26. add(word: string): void {
  27. let current = this.root;
  28. for (const c of word) {
  29. if (current.next.get(c) === null) {
  30. current.next.set(c, new Node());
  31. }
  32. current = current.next.get(c) as Node;
  33. }
  34. if (!current.isWord) {
  35. current.isWord = true;
  36. this.size++;
  37. }
  38. }
  39. /**
  40. * 查询单词 word 是否在 Trie 中
  41. * @param word
  42. */
  43. contains(word: string): boolean {
  44. let current = this.root;
  45. for (const c of word) {
  46. if (current.next.get(c) === null) {
  47. return false;
  48. }
  49. current = current.next.get(c) as Node;
  50. }
  51. return current.isWord;
  52. }
  53. /**
  54. * 查询是否在 Trie 中有单词以 prefix 为前缀
  55. * @param prefix
  56. */
  57. isPrefix(prefix: string): boolean {
  58. let cur = this.root;
  59. for (const c of prefix) {
  60. if (cur.next.get(c) === null) {
  61. return false;
  62. }
  63. cur = cur.next.get(c) as Node;
  64. }
  65. return true;
  66. }
  67. }

LeetCode 相关题目