-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy path211-design-add-and-search-words-data-structure.py
54 lines (45 loc) · 1.52 KB
/
211-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
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, s):
node = self.root
for c in s:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.is_word = True
def search(self, s):
return self.search_helper(s, self.root, 0)
def search_helper(self, s, node, idx):
for i in range(idx, len(s)):
if s[i] == '.':
for child in node.children.values():
if self.search_helper(s, child, i + 1):
return True
return False
if s[i] not in node.children:
return False
node = node.children[s[i]]
return node.is_word
class WordDictionary:
def __init__(self):
self.trie = Trie()
self.len_set = set()
def addWord(self, word: str) -> None:
self.len_set.add(len(word))
self.trie.insert(word)
def search(self, word: str) -> bool:
if len(word) not in self.len_set:
return False
return self.trie.search(word)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
# time O(nL or 26**L) for search(), O(L) for addWord()
# space O(nL), n is the number of words, L is the max len
# using trie and perform dfs inside trie and prune