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

All LeetCode Questions List 题目汇总

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

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

    Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...

  2. LeetCode 676. Implement Magic Dictionary实现一个魔法字典 (C++/Java)

    题目: Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll ...

  3. Week6 - 676.Implement Magic Dictionary

    Week6 - 676.Implement Magic Dictionary Implement a magic directory with buildDict, and search method ...

  4. LC 676. Implement Magic Dictionary

    Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...

  5. 【LeetCode】676. Implement Magic Dictionary 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典 汉明间距 日期 题目地址:https://le ...

  6. 676. Implement Magic Dictionary

    Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...

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

    Implement a trie with insert, search, and startsWith methods. Example: Trie trie = new Trie(); trie. ...

  8. [Swift]LeetCode676. 实现一个魔法字典 | Implement Magic Dictionary

    Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...

  9. LeetCode - Implement Magic Dictionary

    Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...

随机推荐

  1. hdu3486Interviewe(二分是错的)(ST算法RMQ + 判定上下界枚举)

    题目大意是找最小的m使得前m段中每一段的最大值相加严格大于k,每一段长度为[n/m](n/m向下取整,多余的后半部分部分n-m*[n/m]不要) 先给一段我一开始的思路,和网上许多题解思路一样,但其实 ...

  2. TCP和UDP的常见面试题

    问题1]为什么连接的时候是三次握手,关闭的时候却是四次握手? 答:因为当Server端收到Client端的SYN连接请求报文后,可以直接发送SYN+ACK报文.其中ACK报文是用来应答的,SYN报文是 ...

  3. Python中如何使用线程池和进程池?

    进程池的使用 为什么要有进程池?进程池的概念. 在程序实际处理问题过程中,忙时会有成千上万的任务需要被执行,闲时可能只有零星任务. 那么在成千上万个任务需要被执行的时候,我们就需要去创建成千上万个进程 ...

  4. 斜率优化板题 HDU2829 Lawrence

    题目大意:给定一个长度为nnn的序列,至多将序列分成m+1m+1m+1段,每段序列都有权值,权值为序列内两个数两两相乘之和.求序列权值和最小为多少? 数据规模:m<=n<=1000.m&l ...

  5. [Javascript] Keyword 'in' to check prop exists on Object

    function addTo80(n ) { + n; } function memoizedAddTo80 (fn) { let cache = {}; return (n) => { /*k ...

  6. LeetCode 1093. Statistics from a Large Sample

    原题链接在这里:https://leetcode.com/problems/statistics-from-a-large-sample/ 题目: We sampled integers betwee ...

  7. learning java FileWriter

    import java.io.FileWriter; import java.io.IOException; public class FileWriterTest { public static v ...

  8. WinDbg常用命令系列---反汇编u*

    u, ub, uu (Unassemble) u*命令显示内存中指定程序代码的汇编转换.不要将此命令与~u(解冻线程)命令混淆. u[u|b] Range u[u|b] Address u[u|b] ...

  9. 使用Sublime Text 写Processing

    本来以为是个很简单的事情,没想到一波三折~ 1.下载Sublime Text 3(中文版)并且安装,没啥好说的 2.打开[工具 - 命令面板 - install package],接着就报错了 “Th ...

  10. PKUWC2019 Round 2 没去祭

    因为今年有两场 PKUWC,所以叫 PKUWC2019 Round 2. 因为一些沙雕原因,今年去不了了. Day 0 一如既往,没有集训就去上数学课,今天讲几何变换,一如既往的只会说"少女 ...