Implement Magic Dictionary
此题应该目的还是想利用Trie树实现高效检查,不过因为现在case不多,最朴素的字符串对比加哈希表就能过
class MagicDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.store = collections.defaultdict(set)
def buildDict(self, dict):
"""
Build a dictionary through a list of words
:type dict: List[str]
:rtype: void
"""
for word in dict:
self.store[len(word)].add(word)
def search(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
"""
n = len(word)
if n not in self.store:
return False
for string in self.store[n]:
if self.checkDis(word, string):
return True
return False
def checkDis(self, stringA, stringB):
for i in xrange(len(stringA)):
if stringA[i] != stringB[i]:
return stringA[i + 1:] == stringB[i + 1:]
return False
# Your MagicDictionary object will be instantiated and called as such:
# obj = MagicDictionary()
# obj.buildDict(dict)
# param_2 = obj.search(word)