Skip to content

Commit ac98ea6

Browse files
author
sejineer
committed
design-add-and-search-words-data-structure solution
1 parent f640440 commit ac98ea6

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)