Skip to content

Commit f0fed9f

Browse files
committed
design add and search words data structure solution
1 parent 65d0601 commit f0fed9f

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class WordDictionary:
2+
3+
def __init__(self):
4+
self.root = {"$": False}
5+
6+
def addWord(self, word: str) -> None:
7+
node = self.root
8+
for ch in word:
9+
if ch not in node:
10+
node[ch] = {"$": False}
11+
node = node[ch]
12+
node["$"] = True
13+
14+
def search(self, word: str) -> bool:
15+
def dfs(node, idx):
16+
if idx == len(word):
17+
return node.get("$", False)
18+
19+
ch = word[idx]
20+
21+
if ch == ".":
22+
for key in node:
23+
if key == "$":
24+
continue
25+
if dfs(node[key], idx + 1):
26+
return True
27+
return False
28+
else:
29+
if ch in node:
30+
return dfs(node[ch], idx + 1)
31+
else:
32+
return False
33+
34+
return dfs(self.root, 0)
35+
36+
# Your WordDictionary object will be instantiated and called as such:
37+
# obj = WordDictionary()
38+
# obj.addWord(word)
39+
# param_2 = obj.search(word)
40+

0 commit comments

Comments
 (0)