-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdesign_add_and_search_words_data_structure.py
43 lines (35 loc) · 1.32 KB
/
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
# https://leetcode.com/problems/design-add-and-search-words-data-structure/description/
# git add . && git commit -m "completed design_add_and_search_words_data_structure" && git push && exit
class WordDictionary:
def __init__(self):
self.wd = {}
def addWord(self, word: str) -> None:
current_wd = self.wd
for i in range(len(word)):
if word[i] not in current_wd:
current_wd[word[i]] = {}
current_wd = current_wd[word[i]]
current_wd[None] = None
def search(self, word: str) -> bool:
def helper(i, current_wd):
if i == len(word):
return None in current_wd
if word[i] == ".":
return any(
map(
lambda x: helper(i + 1, current_wd[x])
if x is not None
else False,
current_wd.keys(),
)
)
else:
if word[i] not in current_wd:
return False
else:
return helper(i + 1, current_wd[word[i]])
return helper(0, self.wd)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)