[LeetCode] 676. Implement Magic Dictionary 实现神奇字典

Implement a magic directory with buildDict, and search methods.

For the method buildDict, you‘ll be given a list of non-repetitive words to build a dictionary.

For the method search, you‘ll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified word is in the dictionary you just built.

Example 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

Note:

  1. You may assume that all the inputs are consist of lowercase letters a-z.
  2. For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest.
  3. Please remember to RESET your class variables declared in class MagicDictionary, as static/class variables are persisted across multiple test cases. Please see here for more details.

实现一个神奇字典,包含buildDict和search函数。buildDict函数的功能是能把给的没有重复单词的列表建立一个字典,search函数的功能是存在和这个单词只有一个位置上的字符不同返回true,否则返回false。

Java:

class MagicDictionary {

    Map<String, List<int[]>> map = new HashMap<>();
    /** Initialize your data structure here. */
    public MagicDictionary() {
    }

    /** Build a dictionary through a list of words */
    public void buildDict(String[] dict) {
        for (String s : dict) {
            for (int i = 0; i < s.length(); i++) {
                String key = s.substring(0, i) + s.substring(i + 1);
                int[] pair = new int[] {i, s.charAt(i)};

                List<int[]> val = map.getOrDefault(key, new ArrayList<int[]>());
                val.add(pair);

                map.put(key, val);
            }
        }
    }

    /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
    public boolean search(String word) {
        for (int i = 0; i < word.length(); i++) {
            String key = word.substring(0, i) + word.substring(i + 1);
            if (map.containsKey(key)) {
                for (int[] pair : map.get(key)) {
                    if (pair[0] == i && pair[1] != word.charAt(i)) return true;
                }
            }
        }
        return false;
    }
}

Python:

class MagicDictionary(object):
    def _candidates(self, word):
        for i in xrange(len(word)):
            yield word[:i] + ‘*‘ + word[i+1:]

    def buildDict(self, words):
        self.words = set(words)
        self.near = collections.Counter(cand for word in words
                                        for cand in self._candidates(word))

    def search(self, word):
        return any(self.near[cand] > 1 or
                   self.near[cand] == 1 and word not in self.words
                   for cand in self._candidates(word))

Python:

# Time:  O(n), n is the length of the word
# Space: O(d)

import collections

class MagicDictionary(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        _trie = lambda: collections.defaultdict(_trie)
        self.trie = _trie()

    def buildDict(self, dictionary):
        """
        Build a dictionary through a list of words
        :type dictionary: List[str]
        :rtype: void
        """
        for word in dictionary:
            reduce(dict.__getitem__, word, self.trie).setdefault("_end")

    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
        """
        def find(word, curr, i, mistakeAllowed):
            if i == len(word):
                return "_end" in curr and not mistakeAllowed

            if word[i] not in curr:
                return any(find(word, curr[c], i+1, False) for c in curr if c != "_end")                            if mistakeAllowed else False

            if mistakeAllowed:
                return find(word, curr[word[i]], i+1, True) or                        any(find(word, curr[c], i+1, False)                            for c in curr if c not in ("_end", word[i]))
            return find(word, curr[word[i]], i+1, False)

        return find(word, self.trie, 0, True)  

C++:

class MagicDictionary {
public:
    /** Initialize your data structure here. */
    MagicDictionary() {}

    /** Build a dictionary through a list of words */
    void buildDict(vector<string> dict) {
        for (string word : dict) {
            m[word.size()].push_back(word);
        }
    }

    /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
    bool search(string word) {
        for (string str : m[word.size()]) {
            int cnt = 0, i = 0;
            for (; i < word.size(); ++i) {
                if (word[i] == str[i]) continue;
                if (word[i] != str[i] && cnt == 1) break;
                ++cnt;
            }
            if (i == word.size() && cnt == 1) return true;
        }
        return false;
    }

private:
    unordered_map<int, vector<string>> m;
};  

C++:

class MagicDictionary {
public:
    /** Initialize your data structure here. */
    MagicDictionary() {}

    /** Build a dictionary through a list of words */
    void buildDict(vector<string> dict) {
        for (string word : dict) s.insert(word);
    }

    /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
    bool search(string word) {
        for (int i = 0; i < word.size(); ++i) {
            char t = word[i];
            for (char c = ‘a‘; c <= ‘z‘; ++c) {
                if (c == t) continue;
                word[i] = c;
                if (s.count(word)) return true;
            }
            word[i] = t;
        }
        return false;
    }

private:
    unordered_set<string> s;
};

  

  

  

类似题目:

[LeetCode] 208. Implement Trie (Prefix Tree) 实现字典树(前缀树)

720. Longest Word in Dictionary

原文地址:https://www.cnblogs.com/lightwindy/p/9808248.html

时间: 2024-09-29 07:53:39

[LeetCode] 676. Implement Magic Dictionary 实现神奇字典的相关文章

LC 676. Implement Magic Dictionary

Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary. For the method search, you'll be given a word, and judge whether if you modify exactly one

LeetCode - Implement Magic Dictionary

Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary. For the method search, you'll be given a word, and judge whether if you modify exactly one

【LeetCode】Implement strStr()

Implement strStr() Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 标准KMP算法.可参考下文. http://blog.csdn.net/yaochunnian/article/details/7059486 核心思想在于求出模式串前缀与后缀中重复部分,将重复信息保存在n

LeetCode 225 Implement Stack using Queues(用队列来实现栈)(*)

翻译 用队列来实现栈的例如以下操作. push(x) -- 将元素x加入进栈 pop() -- 从栈顶移除元素 top() -- 返回栈顶元素 empty() -- 返回栈是否为空 注意: 你必须使用一个仅仅有标准操作的队列. 也就是说,仅仅有push/pop/size/empty等操作是有效的. 队列可能不被原生支持.这取决于你所用的语言. 仅仅要你仅仅是用queue的标准操作,你能够用list或者deque(double-ended queue)来模拟队列. 你能够如果全部的操作都是有效的(

LeetCode 232 Implement Queue using Stacks(用栈来实现队列)(*)

翻译 用栈来实现队列的下列操作. push(x) -- 将元素x写入到队列的尾部 pop() -- 从队列首部移除元素 peek() -- 返回队列首部元素 empty() -- 返回队列是否为空 注意: 你必须使用一个只有标准操作的栈. 也就是说,只有push/pop/size/empty等操作是有效的. 栈可能不被原生支持,这取决于你所用的语言. 只要你只是用stack的标准操作,你可以用list或者deque(double-ended queue)来模拟栈. 你可以假设所有的操作都是有效的

[LeetCode] 028. Implement strStr() (Easy) (C++/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 028. Implement strStr() (Easy) 链接: 题目:https://oj.leetcode.com/problems/implement-strstr/ 代码(github):https://github.com/illuz/leetcode 题意: 在一个字符串里找另一个字符串在其中的位置

[LeetCode] 232. Implement Queue using Stacks 用栈来实现队列

Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. Notes: You

[LeetCode] Longest Word in Dictionary through Deleting 删除后得到的字典中的最长单词

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographic

[LeetCode] Implement Trie (Prefix Tree) 实现字典树(前缀树)

Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs are consist of lowercase letters a-z. http://dongxicheng.org/structure/trietree/