-
Notifications
You must be signed in to change notification settings - Fork 0
/
prefix_tree.py
54 lines (41 loc) · 1.16 KB
/
prefix_tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'''
Trie (prefix-tree) is a data structure supports word
search and word's prefix search by O(L) time, where L is the word's
length
Created on May 6, 2019
@author: tonytan4ever
'''
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
self.word = None
class Trie:
def __init__(self):
self.root = TrieNode()
def add(self, word, cache_word=True):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_word = True
if cache_word:
node.word = word
def search(self, word):
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_word
def is_prefix(self, prefix):
node = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
if __name__ == '__main__':
# (TODO): Add more tests here...
pass