44 lines
1016 B
Python
44 lines
1016 B
Python
class TrieNode:
|
|
def __init__(self):
|
|
self.children = {}
|
|
self.is_end = False
|
|
|
|
|
|
class Trie:
|
|
def __init__(self):
|
|
self.root = TrieNode()
|
|
|
|
def insert(self, word):
|
|
node = self.root
|
|
for ch in word:
|
|
if ch not in node.children:
|
|
node.children[ch] = TrieNode()
|
|
node = node.children[ch]
|
|
node.is_end = True
|
|
|
|
def search(self, word):
|
|
node = self.root
|
|
for ch in word:
|
|
if ch not in node.children:
|
|
return False
|
|
node = node.children[ch]
|
|
return node.is_end
|
|
|
|
def startsWith(self, prefix):
|
|
node = self.root
|
|
for ch in prefix:
|
|
if ch not in node.children:
|
|
return False
|
|
node = node.children[ch]
|
|
return True
|
|
|
|
|
|
if __name__ == "__main__":
|
|
t = Trie()
|
|
t.insert("apple")
|
|
print(t.search("apple"))
|
|
print(t.search("app"))
|
|
print(t.startsWith("app"))
|
|
t.insert("app")
|
|
print(t.search("app"))
|