-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path211_AddandSearchWord-Datastructuredesign.py
More file actions
41 lines (36 loc) · 1.16 KB
/
211_AddandSearchWord-Datastructuredesign.py
File metadata and controls
41 lines (36 loc) · 1.16 KB
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
class WordDictionary(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.word_dict = collections.defaultdict(list)
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
if word:
self.word_dict[len(word)].append(word)
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
"""
if not word:
return False
if '.' not in word:
return word in self.word_dict[len(word)]
for v in self.word_dict[len(word)]:
for i, ch in enumerate(word):
if ch != v[i] and ch != '.':
break
else:
return True
return False
# Your WordDictionary object will be instantiated and called as such:
# wordDictionary = WordDictionary()
# wordDictionary.addWord("word")
# wordDictionary.search("pattern")