classMagicDictionary:def__init__(self):"""
Initialize your data structure here.
"""
self.trie =dict()#构建字典树defbuildDict(self, words):"""
Build a dictionary through a list of words
"""
node = self.trie
for w in words:#遍历构建的单词列表for c in w:#遍历每个单词的每个字母元素if c notin node:
node[c]=dict()#构建子字典树
node = node[c]
node['#']={}#单词结束符
node = self.trie #重置指针defsearch(self, word):"""
Returns if there is any word in the trie that equals to the given word after modifying exactly one character
"""deffind(word, node):#查找word是否存在于给出的字典树node中for u in word:if u notin node:returnFalse
node=node[u]return'#'in node
defsearchResult(word, node, diff):#递归调用自身ifnot word:return diff==1and'#'in node #递归结束条件,差异为1位,并且单词结束
res =Falseif diff:# 已有一位字符与word不同return find(word, node)for u in node:
res |= searchResult(word[1:], node[u],0if word[0]==u else1)return res
return searchResult(word, self.trie,0)
大佬代码-++
classMagicDictionary(object):def__init__(self):"""
Initialize your data structure here.
"""
self.lists = collections.defaultdict(list)defbuildDict(self,dict):"""
Build a dictionary through a list of words
:type dict: List[str]
:rtype: None
"""for word indict:
self.lists[len(word)].append(word)defsearch(self, word):"""
Returns if there is any word in the trie that equals to the given word after modifying exactly one character
:type word: str
:rtype: bool
"""returnany(sum(a!=b for a,b inzip(word, candidate))==1for candidate in self.lists[len(word)])