您的位置:首页 > 编程语言 > Python开发

leetcode 211. Add and Search Word - Data structure design

2017-08-15 14:03 477 查看
class WordDictionary(object):
""" https://discuss.leetcode.com/topic/29809/python-168ms-beat-100-solution """

def __init__(self):
"""
Initialize your data structure here.
"""
self.words = collections.defaultdict(list)

def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
self.words[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
"""
for a in self.words[len(word)]:
for i,c in enumerate(word):
if a[i] != c and c != '.':
break
else:
return True
return False

# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息