[leetcode trie]208. Implement Trie (Prefix Tree)

Posted wilderness

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode trie]208. Implement Trie (Prefix Tree)相关的知识,希望对你有一定的参考价值。

实现一个字典树

 1 class Trie(object):
 2 
 3     def __init__(self):
 4         self.root = TrieNode()
 5 
 6     def insert(self, word):
 7         cur = self.root
 8         for i in word:
 9             cur = cur.children[i]
10         cur.is_word = True
11         
12 
13     def search(self, word):
14         cur = self.root
15         for i in word:
16             cur = cur.children.get(i)
17             if cur is None:
18                 return False
19         return cur.is_word
20 
21     def startsWith(self, prefix):
22         cur = self.root
23         for i in prefix:
24             cur = cur.children.get(i)
25             if cur is None:
26                 return False
27         return True
28         
29 class TrieNode(object):
30     def __init__(self):
31         self.children = collections.defaultdict(TrieNode)
32         self.is_word = False

 

以上是关于[leetcode trie]208. Implement Trie (Prefix Tree)的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]208. 实现 Trie (前缀树)

leetcode 208. 实现 Trie (前缀树)

leetcode 208. 实现 Trie (前缀树)/字典树

[LeetCode] 208. Implement Trie (Prefix Tree)

[LeetCode] 208. Implement Trie (Prefix Tree)

[LeetCode] 208. 实现 Trie (前缀树)