Skip to content

Commit 95b8c70

Browse files
committed
design add and search words data structure solution
1 parent 1726a64 commit 95b8c70

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class WordDictionary:
2+
3+
def __init__(self):
4+
self.children = {} # key: character, value: WordDictionary node
5+
self.is_end = False
6+
7+
# Time Complexity: O(n), n - length of the word
8+
# Space Complexity: O(N * n), N - number of words, n - length of the word
9+
def addWord(self, word: str) -> None:
10+
cur = self
11+
12+
for char in word:
13+
if char not in cur.children:
14+
cur.children[char] = WordDictionary()
15+
cur = cur.children[char]
16+
17+
cur.is_end = True
18+
19+
# Time Complexity: O(26^n), n - length of the word
20+
# Space Complexity: O(n^2), n - length of the word
21+
def search(self, word: str) -> bool:
22+
cur = self
23+
24+
for i, char in enumerate(word):
25+
if char == ".":
26+
for child in cur.children.values():
27+
if child.search(word[i + 1:]):
28+
return True
29+
return False
30+
31+
elif char not in cur.children:
32+
return False
33+
34+
cur = cur.children[char]
35+
36+
return cur.is_end
37+
38+
# Your WordDictionary object will be instantiated and called as such:
39+
# obj = WordDictionary()
40+
# obj.addWord(word)
41+
# param_2 = obj.search(word)

0 commit comments

Comments
 (0)