更改

跳到导航 跳到搜索
添加1,082字节 、 2021年10月15日 (五) 21:20
建立内容为“Category:刷题 字典树。 <syntaxhighlight lang=python> class Trie: def __init__(self): self.children = defaultdict(Trie) self.isword…”的新页面
[[Category:刷题]]
字典树。

<syntaxhighlight lang=python>
class Trie:
def __init__(self):
self.children = defaultdict(Trie)
self.isword = False

def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
t = self
for c in word:
t = t.children[c]
t.isword = True

def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
t = self
for c in word:
if c in t.children:
t = t.children[c]
else:
return False
return t.isword

def startsWith(self, prefix: str) -> bool:
"""Returns if there is any word in the trie that starts with the given prefix."""
t = self
for c in prefix:
if c in t.children:
t = t.children[c]
else:
return False
return True
</syntaxhighlight>

== 相关题目 ==

=== [https://leetcode.com/problems/implement-trie-prefix-tree/ LeetCode 208. Implement Trie (Prefix Tree)] ===

导航菜单