Skip to content

Commit cbb9ec3

Browse files
authored
Create trie树.md
1 parent 5a38da8 commit cbb9ec3

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

杂项/trie树.md

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
2+
# Trie树的简单实现
3+
1. 构建trie树
4+
2. 查找是否在trie树中。
5+
6+
TODO:
7+
自动补全功能
8+
9+
10+
```python
11+
# coding=utf-8
12+
13+
14+
class Trie:
15+
16+
def __init__(self):
17+
18+
# 入口节点
19+
self.__root = {}
20+
21+
def build(self, temp_str):
22+
23+
if temp_str is None or len(temp_str) == 0:
24+
return
25+
26+
temp_list = list(temp_str)
27+
28+
node = self.__root
29+
30+
for item in temp_list:
31+
if item not in node:
32+
node[item] = {}
33+
node = node[item]
34+
35+
def search(self, temp_str):
36+
37+
if temp_str is None or len(temp_str) == 0:
38+
return
39+
40+
temp_list = list(temp_str)
41+
42+
node = self.__root
43+
44+
for item in temp_list:
45+
if item in node:
46+
node = node[item]
47+
else:
48+
return False
49+
return True
50+
51+
52+
trie = Trie()
53+
trie.build('abcd')
54+
trie.build('abd')
55+
print(trie.search('abe'))
56+
57+
```

0 commit comments

Comments
 (0)