classTrieNode:def__init__(self):
self.children ={}
self.isWord =FalseclassTrie:def__init__(self):"""
Initialize your data structure here.
"""
self.root=TrieNode()definsert(self, word):"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
cur=self.root
for w in word:ifnot w in cur.children:
cur.children[w]=TrieNode()
cur=cur.children[w]
cur.isWord=Truedefsearch(self, word):"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
cur=self.root
for w in word:ifnot w in cur.children:returnFalse
cur=cur.children[w]return cur.isWord
defstartsWith(self, prefix):"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
cur=self.root
for w in prefix:ifnot w in cur.children:returnFalse
cur=cur.children[w]returnTrue
import collections
classNode(object):def__init__(self):
self.children = collections.defaultdict(Node)
self.isword =FalseclassTrie(object):def__init__(self):"""
Initialize your data structure here.
"""
self.root = Node()definsert(self, word):"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
current = self.root
for w in word:
current = current.children[w]
current.isword =Truedefsearch(self, word):"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
current = self.root
for w in word:
current = current.children.get(w)if current ==None:returnFalsereturn current.isword
defstartsWith(self, prefix):"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
current = self.root
for w in prefix:
current = current.children.get(w)if current ==None:returnFalsereturnTrue