File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import Dict
2
+
3
+
4
+ class Trie :
5
+ def __init__ (self ):
6
+ self .children : Dict [str , "Trie" ] = {}
7
+ self .is_end_of_word : bool = False
8
+
9
+ def insert (self , word : str ) -> None :
10
+ node : Trie = self
11
+
12
+ for char in word :
13
+ if char not in node .children :
14
+ node .children [char ] = Trie ()
15
+
16
+ node = node .children [char ]
17
+
18
+ node .is_end_of_word = True
19
+
20
+
21
+ class WordDictionary :
22
+ def __init__ (self ):
23
+ self .trie : Trie = Trie ()
24
+
25
+ def addWord (self , word : str ) -> None :
26
+ self .trie .insert (word )
27
+
28
+ def search (self , word : str ) -> bool :
29
+ def searchInNode (node : Trie , word : str ) -> bool :
30
+ for i , char in enumerate (word ):
31
+ if char == "." :
32
+ # If the current character is '.', check all possible nodes at this level
33
+ for child in node .children .values ():
34
+ if searchInNode (child , word [i + 1 :]):
35
+ return True
36
+
37
+ return False
38
+ else :
39
+ # If the current character is not in the children, return False
40
+ if char not in node .children :
41
+ return False
42
+
43
+ node = node .children [char ]
44
+
45
+ return node .is_end_of_word
46
+
47
+ return searchInNode (self .trie , word )
You can’t perform that action at this time.
0 commit comments