We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 47835c3 commit 31b4c4aCopy full SHA for 31b4c4a
python/design_add_and_search_words_data_structure.py
@@ -0,0 +1,37 @@
1
+class Trienode:
2
+ def __init__(self):
3
+ self.children = {}
4
+ self.word = False
5
+
6
+class WordDictionary:
7
8
9
+ self.root = Trienode()
10
11
12
+ def addWord(self, word: str) -> None:
13
+ ptr = self.root
14
+ for ch in word:
15
+ if ch not in ptr.children:
16
+ ptr.children[ch] = Trienode()
17
+ ptr = ptr.children[ch]
18
+ ptr.word = True
19
20
21
+ def search(self, word: str) -> bool:
22
+ def dfs(j, root):
23
+ curr = root
24
+ for i in range(j, len(word)):
25
+ ch = word[i]
26
+ if ch == ".":
27
+ for child in curr.children.values():
28
+ if dfs(i+1, child):
29
+ return True
30
+ return False
31
+ else:
32
+ if ch not in curr.children:
33
34
+ curr = curr.children[ch]
35
+ return curr.word
36
+ return dfs(0, self.root)
37
0 commit comments