字典树

字典树

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
class TrieNode:

# Trie node class
def __init__(self):
self.children = [None] * 26

# isEndOfWord is True if node represent the end of the word
self.isEndOfWord = False


class Trie:

# Trie data structure class
def __init__(self):
self.root = self.getNode()

def getNode(self):

# Returns new trie node (initialized to NULLs)
return TrieNode()

def _charToIndex(self, ch):

# private helper function
# Converts key current character into index
# use only 'a' through 'z' and lower case

return ord(ch) - ord('a')

def insert(self, key):

# If not present, inserts key into trie
# If the key is prefix of trie node,
# just marks leaf node
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])

# if current character is not present
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]

# mark last node as leaf
pCrawl.isEndOfWord = True

def search(self, key):

# Search key in the trie
# Returns true if key presents
# in trie, else false
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]

return pCrawl.isEndOfWord

参考资料

Trie


字典树
https://wangqian0306.github.io/2021/tire_tree/
作者
WangQian
发布于
2021年11月23日
许可协议