File tree 1 file changed +64
-0
lines changed
1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Trie :
2
+ """
3
+ 208. 实现 Trie (前缀树)
4
+ https://leetcode-cn.com/problems/implement-trie-prefix-tree/
5
+ 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
6
+ """
7
+ def __init__ (self ):
8
+ """
9
+ Initialize your data structure here.
10
+ """
11
+ self .lookup = {}
12
+
13
+
14
+ def insert (self , word : str ) -> None :
15
+ """
16
+ Inserts a word into the trie.
17
+ """
18
+ tree = self .lookup
19
+ for a in word :
20
+ if a not in tree :
21
+ tree [a ] = {}
22
+
23
+ tree = tree [a ]
24
+ tree ['#' ] = '#'
25
+
26
+
27
+ def search (self , word : str ) -> bool :
28
+ """
29
+ Returns if the word is in the trie.
30
+ """
31
+ tree = self .lookup
32
+ for a in word :
33
+ if a not in tree :
34
+ return False
35
+
36
+ tree = tree [a ]
37
+
38
+ if '#' in tree :
39
+ return True
40
+
41
+ return False
42
+
43
+
44
+ def startsWith (self , prefix : str ) -> bool :
45
+ """
46
+ Returns if there is any word in the trie that starts with the given prefix.
47
+ """
48
+ tree = self .lookup
49
+ for a in prefix :
50
+ if a not in tree :
51
+ return False
52
+
53
+ tree = tree [a ]
54
+
55
+ return True
56
+
57
+
58
+ trie = Trie ()
59
+ trie .insert ("apple" )
60
+ trie .search ("apple" )
61
+ trie .search ("app" )
62
+ trie .startsWith ("app" )
63
+ trie .insert ("app" )
64
+ trie .search ("app" )
You can’t perform that action at this time.
0 commit comments