-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy path0211-design-add-and-search-words-data-structure.py
51 lines (44 loc) · 1.43 KB
/
0211-design-add-and-search-words-data-structure.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# time complexity: O(M)
# space complexity: O(M)
class TrieNode:
def __init__(self):
self.children = {}
self.isEnd = False
class WordDictionary:
def __init__(self):
self.root = TrieNode()
self.maxLen = 0
def addWord(self, word: str) -> None:
node = self.root
l = 0
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
l += 1
self.maxLen = max(self.maxLen, l)
node.isEnd = True
def search(self, word: str) -> bool:
if len(word) > self.maxLen:
return False
def helper(idx, node):
for i in range(idx, len(word)):
if word[i] == ".":
for child in node.children.values():
if helper(i + 1, child):
return True
return False
else:
if word[i] not in node.children:
return False
node = node.children[word[i]]
return node.isEnd
return helper(0, self.root)
wordDictionary = WordDictionary()
wordDictionary.addWord("bad")
wordDictionary.addWord("dad")
wordDictionary.addWord("mad")
print(wordDictionary.search("pad"))
print(wordDictionary.search("bad"))
print(wordDictionary.search(".ad"))
print(wordDictionary.search("b.."))