-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0211-design-add-and-search-words-data-structure.py
More file actions
48 lines (38 loc) · 1.29 KB
/
0211-design-add-and-search-words-data-structure.py
File metadata and controls
48 lines (38 loc) · 1.29 KB
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
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
currLen = 0
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
currLen += 1
self.maxLen = max(self.maxLen, currLen)
node.isEnd = True
def search(self, word: str) -> bool:
if len(word) > self.maxLen:
return False
def dfs(idx, node):
for i in range(idx, len(word)):
if word[i] == '.':
for child in node.children.values():
if dfs(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 dfs(0, self.root)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)