File tree 1 file changed +57
-0
lines changed
1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
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
+ ```
You can’t perform that action at this time.
0 commit comments