-
Notifications
You must be signed in to change notification settings - Fork 0
/
Design Add and Search Words Data Structure.py
46 lines (37 loc) · 1.31 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
class Node:
def __init__(self):
self.children = [None] * 26
self.ended = False
class WordDictionary:
def __init__(self):
self.root = Node()
def addWord(self, word: str) -> None:
current = self.root
for letter in word:
index = ord(letter) - ord('a')
if not current.children[index]:
current.children[index] = Node()
current = current.children[index]
current.ended = True
def search(self, word: str) -> bool:
def find(index: int, node: Node(), word: str) -> bool:
if index == len(word):
return node.ended
if word[index] != '.':
i = ord(word[index]) - ord('a')
node = node.children[i]
if not node:
return False
return find(index + 1, node, word)
else:
for i in range(26):
if (not node.children[i]):
continue
if find(index + 1, node.children[i], word):
return True
return False
return find(0, self.root, word)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)