File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +33
-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 .is_end = False
5
+
6
+ class WordDictionary :
7
+
8
+ def __init__ (self ):
9
+ self .root = TrieNode ()
10
+
11
+ def addWord (self , word ):
12
+ node = self .root
13
+ for ch in word :
14
+ if ch not in node .children :
15
+ node .children [ch ] = TrieNode ()
16
+ node = node .children [ch ]
17
+ node .is_end = True
18
+
19
+ def search (self , word ):
20
+ def dfs (index , node ):
21
+ if index == len (word ):
22
+ return node .is_end
23
+ ch = word [index ]
24
+ if ch == '.' :
25
+ for child in node .children .values ():
26
+ if dfs (index + 1 , child ):
27
+ return True
28
+ return False
29
+ if ch in node .children :
30
+ return dfs (index + 1 , node .children [ch ])
31
+ return False
32
+
33
+ return dfs (0 , self .root )
You can’t perform that action at this time.
0 commit comments