We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 45f2351 commit f77766bCopy full SHA for f77766b
211-Design-Add-and-Search-Words-Data-Structure.py
@@ -0,0 +1,35 @@
1
+class TrieNode:
2
+ def __init__(self):
3
+ self.children = {} # a : TrieNode
4
+ self.word = False
5
+
6
+class WordDictionary:
7
8
+ self.root = TrieNode()
9
10
+ def addWord(self, word: str) -> None:
11
+ cur = self.root
12
+ for c in word:
13
+ if c not in cur.children:
14
+ cur.children[c] = TrieNode()
15
+ cur = cur.children[c]
16
+ cur.word = True
17
18
+ def search(self, word: str) -> bool:
19
+ def dfs(j, root):
20
+ cur = root
21
22
+ for i in range(j, len(word)):
23
+ c = word[i]
24
+ if c == ".":
25
+ for child in cur.children.values():
26
+ if dfs(i + 1, child):
27
+ return True
28
+ return False
29
+ else:
30
31
32
33
+ return cur.word
34
35
+ return dfs(0, self.root)
0 commit comments