首页 > 代码库 > [leetcode trie]208. Implement Trie (Prefix Tree)
[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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。