
题解
这道题的目的是实现一个 Trie 数据结构,Trie 实现相对简单:
class TrieNode {isWord: boolean;next: Map<string, TrieNode> = new Map()constructor(isWord = false) {this.isWord = isWord}}class Trie {root: TrieNodeconstructor() {this.root = new TrieNode()}insert(word: string): void {// 1. 遍历 word 中的每一个字符// 2. 查看字符是否已经存在于 TrieNode 中,如果不存在,则将该字符存到 Trie 中// 3. 最后一个字符标记为单词的结尾let current = this.rootfor(const c of word) {if (!current.next.get(c)) {current.next.set(c, new TrieNode())}current = current.next.get(c) as TrieNode}current.isWord = true}search(word: string): boolean {// 1. 遍历 word 中的每一个字符// 2. 如果某个字符不存在,则返回 false// 3. 如果已经遍历到最后一个字符,并且都存在 Trie 中,那么则判断最后一个字符是否有 isWord 的标识let current = this.rootfor(const c of word) {if (current.next === null) {return false}const nextTrieNode = current.next.get(c)if (!nextTrieNode) {return false}current = nextTrieNode}return current.isWord}startsWith(prefix: string): boolean {// 1. 遍历 prefix 中的每一个字符// 2. 如果某个字符不存在,直接返回 false,否则返回 truelet current = this.rootfor(const c of prefix) {if (current.next === null) {return false}const nextTrieNode = current.next.get(c)if (!nextTrieNode) {return false}current = nextTrieNode}return true}}/*** Your Trie object will be instantiated and called as such:* var obj = new Trie()* obj.insert(word)* var param_2 = obj.search(word)* var param_3 = obj.startsWith(prefix)*/
