File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Trienode :
2
+ def __init__ (self ):
3
+ self .children = {}
4
+ self .word = False
5
+
6
+ class WordDictionary :
7
+
8
+ def __init__ (self ):
9
+ self .root = Trienode ()
10
+
11
+
12
+ def addWord (self , word : str ) -> None :
13
+ ptr = self .root
14
+ for ch in word :
15
+ if ch not in ptr .children :
16
+ ptr .children [ch ] = Trienode ()
17
+ ptr = ptr .children [ch ]
18
+ ptr .word = True
19
+
20
+
21
+ def search (self , word : str ) -> bool :
22
+ def dfs (j , root ):
23
+ curr = root
24
+ for i in range (j , len (word )):
25
+ ch = word [i ]
26
+ if ch == "." :
27
+ for child in curr .children .values ():
28
+ if dfs (i + 1 , child ):
29
+ return True
30
+ return False
31
+ else :
32
+ if ch not in curr .children :
33
+ return False
34
+ curr = curr .children [ch ]
35
+ return curr .word
36
+ return dfs (0 , self .root )
37
+
You can’t perform that action at this time.
0 commit comments