Skip to content

Commit f77766b

Browse files
authored
Create 211-Design-Add-and-Search-Words-Data-Structure.py
1 parent 45f2351 commit f77766b

File tree

1 file changed

+35
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)