676. 实现一个魔法字典




class MagicDictionary(object):
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.mydict = {}

    def buildDict(self, dictionary):
        """
        :type dictionary: List[str]
        :rtype: None
        """
        for word in dictionary:
            self.mydict[word] = len(word)

    def search(self, searchWord):
        """
        :type searchWord: str
        :rtype: bool
        """
        # 特判:没有相同长度的单词,肯定为False
        if len(searchWord) not in self.mydict.values():
            return False
        # 长度相同,但单词不同,且不同字符只有一个,才能返回True,否则返回False
        for word, wordSize in self.mydict.items():
            if len(searchWord) == wordSize and searchWord != word and self.canTrans(searchWord, word, wordSize):
                return True
        return False

    def canTrans(self, searchWord, word, wordSize):
        flag = 0
        for i in range(wordSize):
            if searchWord[i] != word[i]:
                flag += 1
        return flag == 1
posted @ 2020-11-23 16:09  人间烟火地三鲜  阅读(96)  评论(0编辑  收藏  举报