-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathdesign-add-and-search-words-data-structure.py
57 lines (42 loc) · 1.5 KB
/
design-add-and-search-words-data-structure.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from typing import Dict, Optional
class TrieNode:
def __init__(self, val: str) -> None:
self.val = val
self.children: Dict[str, TrieNode] = {}
self.end = False
self.word: Optional[str] = None
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self._trie = TrieNode(None)
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
node = self._trie
for letter in word:
node.children.setdefault(letter, TrieNode(letter))
node = node.children[letter]
node.end = True
node.word = word
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the
dot character '.' to represent any one letter.
"""
def backtrack(node: TrieNode, word: str, pos: int) -> bool:
if pos == len(word):
return node.end
letters = node.children.keys() if word[pos] == "." else word[pos]
for next_letter in letters:
if next_letter in node.children:
if backtrack(node.children[next_letter], word, pos + 1):
return True
return False
return backtrack(self._trie, word, 0)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)