Skip to content

Commit 88cddc9

Browse files
committed
solve: design word dictionary
1 parent b4bea64 commit 88cddc9

File tree

1 file changed

+47
-0
lines changed
  • design-add-and-search-words-data-structure

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from typing import Dict
2+
3+
4+
class Trie:
5+
def __init__(self):
6+
self.children: Dict[str, "Trie"] = {}
7+
self.is_end_of_word: bool = False
8+
9+
def insert(self, word: str) -> None:
10+
node: Trie = self
11+
12+
for char in word:
13+
if char not in node.children:
14+
node.children[char] = Trie()
15+
16+
node = node.children[char]
17+
18+
node.is_end_of_word = True
19+
20+
21+
class WordDictionary:
22+
def __init__(self):
23+
self.trie: Trie = Trie()
24+
25+
def addWord(self, word: str) -> None:
26+
self.trie.insert(word)
27+
28+
def search(self, word: str) -> bool:
29+
def searchInNode(node: Trie, word: str) -> bool:
30+
for i, char in enumerate(word):
31+
if char == ".":
32+
# If the current character is '.', check all possible nodes at this level
33+
for child in node.children.values():
34+
if searchInNode(child, word[i + 1 :]):
35+
return True
36+
37+
return False
38+
else:
39+
# If the current character is not in the children, return False
40+
if char not in node.children:
41+
return False
42+
43+
node = node.children[char]
44+
45+
return node.is_end_of_word
46+
47+
return searchInNode(self.trie, word)

0 commit comments

Comments
 (0)