File tree Expand file tree Collapse file tree
design-add-and-search-words-data-structure Expand file tree Collapse file tree 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+ def addWord (self , word : str ) -> None :
12+ curr = self .root
13+ for c in word :
14+ if c not in curr .children :
15+ curr .children [c ] = TrieNode ()
16+ curr = curr .children [c ]
17+ curr .word = True
18+
19+ def search (self , word : str ) -> bool :
20+
21+ def dfs (j , root ):
22+ curr = root
23+
24+ for i in range (j , len (word )):
25+ c = word [i ]
26+
27+ if c == "." :
28+ for child in curr .children .values ():
29+ if dfs (i + 1 , child ):
30+ return True
31+ return False
32+ else :
33+ if c not in curr .children :
34+ return False
35+ curr = curr .children [c ]
36+ return curr .word
37+ return dfs (0 , self .root )
38+
39+ # Your WordDictionary object will be instantiated and called as such:
40+ # obj = WordDictionary()
41+ # obj.addWord(word)
42+ # param_2 = obj.search(word)
You can’t perform that action at this time.
0 commit comments