Trie 树,也叫字典树,它是一个多叉树。它是一种专门处理字符串匹配的数据结构,用来解决在一组字符串集合中快速查找某个字符串的问题。其本质就是利用字符串之间的公共前缀,将重复的前缀合并在一起。
Trie 可视化:https://www.cs.usfca.edu/~galles/visualization/Trie.html
Trie 的基础知识可以查看 算法与数据结构之美——35 | Trie树:如何实现搜索引擎的搜索关键词提示功能?
class Node {isWord: boolean;next: Map<string, Node>;constructor(isWord = false) {this.isWord = isWord;this.next = new Map();}}interface TrieInterface {root: Node;size: number;getSize: () => number;add: (word: string) => void;contains: (word: string) => boolean;}class Trie implements TrieInterface {root = new Node();size = 0;getSize(): number {return this.size;}/*** 向 Trie 中添加一个新的单词 word* @param word*/add(word: string): void {let current = this.root;for (const c of word) {if (current.next.get(c) === null) {current.next.set(c, new Node());}current = current.next.get(c) as Node;}if (!current.isWord) {current.isWord = true;this.size++;}}/*** 查询单词 word 是否在 Trie 中* @param word*/contains(word: string): boolean {let current = this.root;for (const c of word) {if (current.next.get(c) === null) {return false;}current = current.next.get(c) as Node;}return current.isWord;}/*** 查询是否在 Trie 中有单词以 prefix 为前缀* @param prefix*/isPrefix(prefix: string): boolean {let cur = this.root;for (const c of prefix) {if (cur.next.get(c) === null) {return false;}cur = cur.next.get(c) as Node;}return true;}}
