Skip to content

Commit f3e127c

Browse files
committed
design add and search words data structure
1 parent 780c0c5 commit f3e127c

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
def addWord(self, word: str) -> None:
12+
curr = self.root
13+
for c in word:
14+
if c not in curr.children:
15+
curr.children[c] = TrieNode()
16+
curr = curr.children[c]
17+
curr.word = True
18+
19+
def search(self, word: str) -> bool:
20+
21+
def dfs(j, root):
22+
curr = root
23+
24+
for i in range(j, len(word)):
25+
c = word[i]
26+
27+
if c == ".":
28+
for child in curr.children.values():
29+
if dfs(i+1, child):
30+
return True
31+
return False
32+
else :
33+
if c not in curr.children:
34+
return False
35+
curr = curr.children[c]
36+
return curr.word
37+
return dfs(0, self.root)
38+
39+
# Your WordDictionary object will be instantiated and called as such:
40+
# obj = WordDictionary()
41+
# obj.addWord(word)
42+
# param_2 = obj.search(word)

0 commit comments

Comments
 (0)