-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd and Search Word - Data structure design.py
85 lines (68 loc) · 2.12 KB
/
Add and Search Word - Data structure design.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
'''
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
Example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.
'''
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class WordDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
node = self.root
for c in word:
if c not in node.children:
tmp = TrieNode()
node.children[c] = tmp
node = node.children[c]
node.is_end = True
def find(self, root, word):
node = root
for i in xrange(len(word)):
if word[i] == '.':
flag = False
for x in node.children:
if self.find(node.children[x], word[i+1:]):
flag = True
break
if flag:
return True
else:
return False
else:
if word[i] not in node.children:
return False
node = node.children[word[i]]
return node != None and node.is_end
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
return self.find(self.root, word)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)