181 - 208 实现前缀树Trie
题目
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
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
说明:
你可以假设所有的输入都是由小写字母 a-z 构成的。
保证所有输入均为非空字符串。
解答
题解把前缀树应用说的很好呀,搜索自动补全、打字预测等等。
前缀树,就是根据字符串前缀来匹配的,数据结构。

哈希表嵌套
https://leetcode.com/problems/implement-trie-prefix-tree/discuss/58834/AC-Python-Solution
每个字母都是一个key,嵌套哈希表。
最后推入一个#,来表明单词的结束。不然app和apple就无法区分了。
Runtime: 112 ms, faster than 99.90% of Python3 online submissions for Implement Trie (Prefix Tree).
Memory Usage: 26.1 MB, less than 66.67% of Python3 online submissions for Implement Trie (Prefix Tree).
用node
Runtime: 216 ms, faster than 32.09% of Python3 online submissions for Implement Trie (Prefix Tree).
Memory Usage: 31.5 MB, less than 7.41% of Python3 online submissions for Implement Trie (Prefix Tree).
Last updated
Was this helpful?