Implement a trie with insert
, search
, and startsWith
methods.
Example:
Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true
Note:
- You may assume that all inputs are consist of lowercase letters
a-z
. - All inputs are guaranteed to be non-empty strings.
LeetCode:链接
字典树:参考链接
本题要求实现字典树。对cat,cash,app,apple,aply,ok 建一颗字典树,建成之后如下图所示:
由此可以看出:
1、字典树用边表示字母。
2、有相同前缀的单词公用前缀节点,那我们可以的得出每个节点最多有26个子节点(在单词只包含小写字母的情况下)。
3、整棵树的根节点是空的。为什么呢?便于插入和查找。
4、每个单词结束的时候用一个特殊字符表示,图中用的‘′,那么从根节点到任意一个‘′,那么从根节点到任意一个‘’所经过的边的所有字母表示一个单词。
class TreeNode(object):
def __init__(self):
self.children = dict()
self.isword = False
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TreeNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
# 用字典表示一个与结点相连的子结点
node = self.root
for letter in word:
child = node.children.get(letter)
if child is None:
child = TreeNode()
node.children[letter] = child
node = child
node.isword = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
# 必须是查找一个完整的单词
node = self.root
for letter in word:
node = node.children.get(letter)
if node is None:
return False
return node.isword
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
node = self.root
for letter in prefix:
node = node.children.get(letter)
if node is None:
return False
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)