classWordDictionary(object):def__init__(self):"""
Initialize your data structure here.
"""
self.d = collections.defaultdict(list)defaddWord(self, word):"""
Adds a word into the data structure.
:type word: str
:rtype: None
"""
self.d[len(word)].append(word)#构建集合,将相同长度的单词存在同一个字典键下defsearch(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
"""#简便写法
n =len(word)
f =lambda s:all(map(lambda i: word[i]in{s[i],'.'},range(n)))#匹配函数,比写正则要快不少,all为必须全部都为True才为Truereturnany(map(f, self.d[n]))#any为只要之中元素有一个True最终结果就为True#拓展写法
n =len(word)deff(s):print(s)for i inrange(n):if word[i]notin{s[i],'.'}:print(s[i])returnFalsereturnTruefor s in self.d[n]:#从相同长度的单词中逐一取出进行比对if f(s):returnTruereturnFalse#正则写法return re.search(word.replace('.','[a-z]'), self.d[len(word)])
递归逐一比对
classWordDictionary:def__init__(self):"""
Initialize your data structure here.
"""from collections import defaultdict
self.lookup ={}defaddWord(self, word):"""
Adds a word into the data structure.
"""
tree = self.lookup
for a in word:
tree = tree.setdefault(a,{})#返回值是插入后的当前元素
tree["#"]={}defsearch(self, word):"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""#{u'b': {u'a': {u'd': {'#': {}}}}, u'm': {u'a': {u'd': {'#': {}}}}, u'd': {u'a': {u'd': {'#': {}}}}}defhelper(word, tree):ifnot word:#word的下一个字符为空表示结束,在字典中正好也是出现了结束符那么代表匹配成功if"#"in tree:returnTrue#匹配成功返回True,否则代表还有更长的单词,就返回FalsereturnFalseif word[0]==".":#如果第一个字符是.,跳过第一个元素对字典中每一个分支进行递归调用for t in tree:# print(tree[t])if helper(word[1:], tree[t]):returnTrueelif word[0]in tree:#如果第一个字符在字典的键值中,将会锁定一个tree的字典分支继续向下进行递归比对print(tree[word[0]])if helper(word[1:], tree[word[0]]):returnTruereturnFalse#第一个字符就不在字典中直接返回Falsereturn helper(word, self.lookup)