Skip to content

Commit cf362f5

Browse files
committed
add design-add-and-search-words-data-structure
1 parent 322bffd commit cf362f5

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
Time complexity O(26^w)
3+
Space complexity O(w)
4+
5+
Trie, DFS
6+
"""
7+
8+
class Node:
9+
def __init__(self, end=False):
10+
self.children = {} # char : node
11+
self.end = end
12+
13+
class WordDictionary:
14+
15+
def __init__(self):
16+
self.root = Node(end=True)
17+
18+
def addWord(self, word: str) -> None:
19+
node = self.root
20+
for ch in word:
21+
if ch not in node.children:
22+
node.children[ch] = Node()
23+
node = node.children[ch]
24+
node.end = True
25+
26+
def search(self, word: str) -> bool:
27+
return self.dfs(self.root, word)
28+
29+
def dfs(self, start, word):
30+
ch = word[0]
31+
if ch == word:
32+
if ch == '.':
33+
return any([node.end for c, node in start.children.items()])
34+
elif ch in start.children:
35+
if start.children[ch].end:
36+
return True
37+
return False
38+
39+
if ch == '.':
40+
return any([self.dfs(node, word[1:]) for c, node in start.children.items()])
41+
elif ch in start.children:
42+
return self.dfs(start.children[ch], word[1:])
43+
else:
44+
return False

0 commit comments

Comments
 (0)