-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie_tree.py
44 lines (38 loc) · 1001 Bytes
/
trie_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
class TrieTree:
END = '#'
def __init__(self):
self.root = {}
def add(self, s):
node = self.root
for c in s:
if c not in node:
node[c] = {}
node = node[c]
node[self.END] = self.END
def search(self, s):
node = self.root
for c in s:
if c not in node:
return False
node = node[c]
return self.END in node
def prefix(self, s):
prefix = ''
node = self.root
for c in s:
if self.END in node:
return prefix
if c not in node:
return ''
prefix += c
node = node[c]
if self.END in node:
return prefix
return ''
if __name__ == '__main__':
trie = TrieTree()
trie.add('hello')
trie.add('world')
trie.add('hi')
print('search hello', trie.search('hello'))
print('prefix hi', trie.prefix('hfa'))