Skip to content

Commit 4dc9152

Browse files
Solve : Design Add And Search Words Data Structure
1 parent 7c69408 commit 4dc9152

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class TrieNode:
2+
def __init__(self):
3+
self.children = {}
4+
self.is_end = False
5+
6+
class WordDictionary:
7+
8+
def __init__(self):
9+
self.root = TrieNode()
10+
11+
def addWord(self, word):
12+
node = self.root
13+
for ch in word:
14+
if ch not in node.children:
15+
node.children[ch] = TrieNode()
16+
node = node.children[ch]
17+
node.is_end = True
18+
19+
def search(self, word):
20+
def dfs(index, node):
21+
if index == len(word):
22+
return node.is_end
23+
ch = word[index]
24+
if ch == '.':
25+
for child in node.children.values():
26+
if dfs(index + 1, child):
27+
return True
28+
return False
29+
if ch in node.children:
30+
return dfs(index + 1, node.children[ch])
31+
return False
32+
33+
return dfs(0, self.root)

0 commit comments

Comments
 (0)