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 f640440 commit ac98ea6Copy full SHA for ac98ea6
design-add-and-search-words-data-structure/sejineer.py
@@ -0,0 +1,26 @@
1
+class WordDictionary:
2
+
3
+ def __init__(self):
4
+ self.root = {"$": True}
5
6
7
+ def addWord(self, word: str) -> None:
8
+ node = self.root
9
+ for ch in word:
10
+ if ch not in node:
11
+ node[ch] = {"$": False}
12
+ node = node[ch]
13
+ node["$"] = True
14
15
+ def search(self, word: str) -> bool:
16
+ def dfs(node, idx):
17
+ if idx == len(word):
18
+ return node["$"]
19
+ ch = word[idx]
20
+ if ch in node:
21
+ return dfs(node[ch], idx + 1)
22
+ elif ch == ".":
23
+ return any(dfs(node[k], idx + 1) for k in node if k != "$")
24
+ else:
25
+ return False
26
+ return dfs(self.root, 0)
0 commit comments