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. new 的对象如何不分配在堆而分配在栈上(方法逃逸等)

    当能够明确对象不会发生逃逸时,就可以对这个对象做一个优化,不将其分配到堆上,而是直接分配到栈上,这样在方法结束时,这个对象就会随着方法的出栈而销毁,这样就可以减少垃圾回收的压力. 如方法逃逸. 逃逸分 ...

  2. BZOJ3028 食物 和 LOJ6261 一个人的高三楼

    总结一下广义二项式定理. 食物 明明这次又要出去旅游了,和上次不同的是,他这次要去宇宙探险!我们暂且不讨论他有多么NC,他又幻想了他应该带一些什么东西.理所当然的,你当然要帮他计算携带N件物品的方案数 ...

  3. django-缓存django-redis

    https://django-redis-chs.readthedocs.io/zh_CN/latest/ 安装 django-redis 最简单的方法就是用 pip : pip install dj ...

  4. 数据分析 - Numpy

    简介 Numpy是高性能科学计算和数据分析的基础包.它也是pandas等其他数据分析的工具的基础,基本所有数据分析的包都用过它.NumPy为Python带来了真正的多维数组功能,并且提供了丰富的函数库 ...

  5. mybatis框架-SqlSession会话操作数据库的两种方式

    1.通过SqlSession实力来直接执行已经映射的sql语句 例如,查询整个用户表中的信息 在UserMapper.xml中编写sql语句 编写测试方法: 注意:这里使用的selectList方法: ...

  6. np.mean()函数

    1. 数组的操作: import numpy as np a = np.array([[1, 2], [3, 4]]) print(a) print(type(a)) print(np.mean(a) ...

  7. 使用SpringBoot访问jsp页面

    1 编写application.yml文件 spring: mvc: view: suffix: .jsp prefix: /jsp/ 2 创建Controller层 @Controller @Req ...

  8. art-template模板引擎高级使用

    一.结合express的基本使用 // npm下载express/art-template/express-art-tempalte,并且加载 var express=require('express ...

  9. 【loj3059】【hnoi2019】序列

    题目 给出一个长度为 \(n\) 的序列 \(A\) ; 你需要构造一个新的序列\(B\) ,满足: $B_{i} \le B_{i+1} (1 \le i \lt n ) $ $\sum_{i=1} ...

  10. springMVC开启声明式事务实现操作日志记录

    第一步.在applicationContext-mvc.xml开启AOP注解扫描 <aop:aspectj-autoproxy/> 第二步.创建增强类,实现日志记录 @Component ...