Skip to content

Commit 31b4c4a

Browse files
problem 211: Design Add and Search Words Data Structure
1 parent 47835c3 commit 31b4c4a

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Trienode:
2+
def __init__(self):
3+
self.children = {}
4+
self.word = False
5+
6+
class WordDictionary:
7+
8+
def __init__(self):
9+
self.root = Trienode()
10+
11+
12+
def addWord(self, word: str) -> None:
13+
ptr = self.root
14+
for ch in word:
15+
if ch not in ptr.children:
16+
ptr.children[ch] = Trienode()
17+
ptr = ptr.children[ch]
18+
ptr.word = True
19+
20+
21+
def search(self, word: str) -> bool:
22+
def dfs(j, root):
23+
curr = root
24+
for i in range(j, len(word)):
25+
ch = word[i]
26+
if ch == ".":
27+
for child in curr.children.values():
28+
if dfs(i+1, child):
29+
return True
30+
return False
31+
else:
32+
if ch not in curr.children:
33+
return False
34+
curr = curr.children[ch]
35+
return curr.word
36+
return dfs(0, self.root)
37+

0 commit comments

Comments
 (0)