Skip to content

Latest commit

 

History

History
84 lines (60 loc) · 2.69 KB

676-implement-magic-dictionary.md

File metadata and controls

84 lines (60 loc) · 2.69 KB

676. Implement Magic Dictionary - 实现一个魔法字典

实现一个带有buildDict, 以及 search方法的魔法字典。

对于buildDict方法,你将被给定一串不重复的单词来构建一个字典。

对于search方法,你将被给定一个单词,并且判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。

示例 1:

Input: buildDict(["hello", "leetcode"]), Output: Null
Input: search("hello"), Output: False
Input: search("hhllo"), Output: True
Input: search("hell"), Output: False
Input: search("leetcoded"), Output: False

注意:

  1. 你可以假设所有输入都是小写字母 a-z
  2. 为了便于竞赛,测试所用的数据量很小。你可以在竞赛结束后,考虑更高效的算法。
  3. 请记住重置MagicDictionary类中声明的类变量,因为静态/类变量会在多个测试用例中保留。 请参阅这里了解更多详情。

题目标签:Trie / Hash Table

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
python3 60 ms N/A
import string

class MagicDictionary:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.vals = set()

    def buildDict(self, dict):
        """
        Build a dictionary through a list of words
        :type dict: List[str]
        :rtype: void
        """
        for s in dict:
            sl, tmp = list(s), list(s)
            for i in range(len(sl)):
                for c in 'abcdefghijklmnopqrstuvwxyz':
                    if c != sl[i]:
                        tmp[i] = c
                        self.vals.add(''.join(tmp))
                tmp[i] = sl[i]

    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
        """
        return word in self.vals


# Your MagicDictionary object will be instantiated and called as such:
# obj = MagicDictionary()
# obj.buildDict(dict)
# param_2 = obj.search(word)