upd
This commit is contained in:
43
algorithms/labs/lab8/code/hash/2.py
Normal file
43
algorithms/labs/lab8/code/hash/2.py
Normal file
@@ -0,0 +1,43 @@
|
||||
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"))
|
||||
Reference in New Issue
Block a user