File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ class WordDictionary :
2+
3+ def __init__ (self ):
4+ self .root = {"$" : False }
5+
6+ def addWord (self , word : str ) -> None :
7+ node = self .root
8+ for ch in word :
9+ if ch not in node :
10+ node [ch ] = {"$" : False }
11+ node = node [ch ]
12+ node ["$" ] = True
13+
14+ def search (self , word : str ) -> bool :
15+ def dfs (node , idx ):
16+ if idx == len (word ):
17+ return node .get ("$" , False )
18+
19+ ch = word [idx ]
20+
21+ if ch == "." :
22+ for key in node :
23+ if key == "$" :
24+ continue
25+ if dfs (node [key ], idx + 1 ):
26+ return True
27+ return False
28+ else :
29+ if ch in node :
30+ return dfs (node [ch ], idx + 1 )
31+ else :
32+ return False
33+
34+ return dfs (self .root , 0 )
35+
36+ # Your WordDictionary object will be instantiated and called as such:
37+ # obj = WordDictionary()
38+ # obj.addWord(word)
39+ # param_2 = obj.search(word)
40+
You can’t perform that action at this time.
0 commit comments