-
Notifications
You must be signed in to change notification settings - Fork 33
/
trie.py
69 lines (57 loc) · 1.67 KB
/
trie.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""
@author: liucong
@contact: logcongcong@gmail.com
@time: 2020/7/29 13:40
"""
class Trie:
def __init__(self):
self.root = {}
self.end = -1
def insert(self, word):
curNode = self.root
for c in word:
if not c in curNode:
curNode[c] = {}
curNode = curNode[c]
curNode[self.end] = True
def search(self, word):
curNode = self.root
for c in word:
if not c in curNode:
return False
curNode = curNode[c]
if not self.end in curNode:
return False
return True
def startsWith(self, pcurNodeix):
curNode = self.root
for c in pcurNodeix:
if not c in curNode:
return False
curNode = curNode[c]
return True
def get_start(self, prefix):
def _get_key(pre, pre_node):
words_list = []
if pre_node.is_word:
words_list.append(pre)
for x in pre_node.data.keys():
words_list.extend(_get_key(pre + str(x), pre_node.data.get(x)))
return words_list
words = []
if not self.startsWith(prefix):
return words
if self.search(prefix):
words.append(prefix)
return words
node = self.root
for letter in prefix:
node = node.data.get(letter)
return _get_key(prefix, node)
def enumerateMatch(self, word, space=""):
matched = []
while len(word) > 1:
if self.search(word):
matched.append(space.join(word[:]))
del word[-1]
return matched