1
+ # Design a data structure that supports adding new words and finding if a string matches
2
+ # any previously added string.
3
+
4
+ # Implement the WordDictionary class:
5
+
6
+ # WordDictionary() Initializes the object.
7
+ # void addWord(word) Adds word to the data structure, it can be matched later.
8
+ # bool search(word) Returns true if there is any string in the data structure that matches
9
+ # word or false otherwise. word may contain dots '.' where dots can be matched with any letter.
10
+
11
+
12
+ # Example:
13
+ # Input
14
+ # ["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
15
+ # [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
16
+ # Output
17
+ # [null,null,null,null,false,true,true,true]
18
+
19
+ # Explanation
20
+ # WordDictionary wordDictionary = new WordDictionary();
21
+ # wordDictionary.addWord("bad");
22
+ # wordDictionary.addWord("dad");
23
+ # wordDictionary.addWord("mad");
24
+ # wordDictionary.search("pad"); // return False
25
+ # wordDictionary.search("bad"); // return True
26
+ # wordDictionary.search(".ad"); // return True
27
+ # wordDictionary.search("b.."); // return True
28
+
29
+
30
+ # Constraints:
31
+
32
+ # 1 <= word.length <= 25
33
+ # word in addWord consists of lowercase English letters.
34
+ # word in search consist of '.' or lowercase English letters.
35
+ # There will be at most 2 dots in word for search queries.
36
+ # At most 104 calls will be made to addWord and search.
37
+
38
+
39
+ class TrieNode :
40
+ def __init__ (self ):
41
+ self .children = {}
42
+ self .isWord = False
43
+
44
+ class WordDictionary :
45
+
46
+ def __init__ (self ):
47
+ self .root = TrieNode ()
48
+
49
+ def addWord (self , word : str ) -> None :
50
+ node = self .root
51
+ for char in word :
52
+ if char not in node .children :
53
+ node .children [char ] = TrieNode ()
54
+ node = node .children [char ]
55
+ node .isWord = True
56
+
57
+ def search (self , word : str ) -> bool :
58
+ def find (node , i ):
59
+ if i == len (word ):
60
+ return node .isWord
61
+ char = word [i ]
62
+ if char == '.' :
63
+ for child in node .children .values ():
64
+ if find (child , i + 1 ):
65
+ return True
66
+ return False
67
+ if char not in node .children :
68
+ return False
69
+ return find (node .children [char ], i + 1 )
70
+
71
+ return find (self .root , 0 )
72
+
73
+
74
+ # Your WordDictionary object will be instantiated and called as such:
75
+ # obj = WordDictionary()
76
+ # obj.addWord(word)
77
+ # param_2 = obj.search(word)
0 commit comments