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. monkey内存泄露

    monkey内存泄露 1.内存泄露发现方法 执行monkey测试时有时会有内存泄露情况,可以进行排查 a.手机弹出out of  memory对话框--基本确定有内存泄露 b.手机没有提示但是实际有内 ...

  2. Docker 部署 vue 项目

    Docker 部署 vue 项目 Docker 作为轻量级虚拟化技术,拥有持续集成.版本控制.可移植性.隔离性和安全性等优势.本文使用Docker来部署一个vue的前端应用,并尽可能详尽的介绍了实现思 ...

  3. 编程小白入门分享四:Vue的安装及使用快速入门

    一.VUE简介 vue是一个JavaMVVM库,是一套用于构建用户界面的渐进式框架,是初创项目的首选前端框架.它是以数据驱动和组件化的思想构建的,采用自底向上增量开发的设计.它是轻量级的,它有很多独立 ...

  4. 电脑重装后 python 2 3快速安装

    背景: 电脑重装后,python也要跟着重装,将安装包.环境变量备份等安装完成后直接安装 重装前 1. pip包备份,命令窗口 pip freeze > py2.txt #python2的包 p ...

  5. MERGE引擎 分表后 快速查询所有数据

    MERGE存储引擎把一组MyISAM数据表当做一个逻辑单元来对待,让我们可以同时对他们进行查询.构成一个MERGE数据表结构的各成员MyISAM数据表必须具有完全一样的结构.每一个成员数据表的数据列必 ...

  6. 4、markdown基本语法

    一.前言 由于有些语法无法在博客园展示,推荐使用Typora解锁全套,下载地址:https://www.typora.io/ 推荐使用jupyter,使用方法:https://www.cnblogs. ...

  7. Python 代码混淆和加密技术

    动机 Python进行商业开发时, 需要有一定的安全意识, 为了不被轻易的逆向. 混淆和加密就有所必要了. 混淆 为了增加代码阅读的难度, 源代码的混淆非常必要, 一个在线的Python代码混淆网站. ...

  8. php+tcpdf如何把生成的pdf文件保存在服务端

    tcpdf组件目前应用得非常广泛,但是对于如何把生成的pdf文件自动保存在服务端却很少有人提及.让我们先来看看标准输出代码:   //服务器存档模式 $pdf->Output('output.p ...

  9. 后台增删改查的实现——java基础、jsp、servlet、数据库

    1.前台和后台的关系: 后台是由工作人员操作的,通过后台系统对数据库实行增删改查等操作,通过前台系统访问数据库,将数据库中的信息通过前台显示. 2.功能实现: (1)显示全部商品信息: home.js ...

  10. BZOJ 1477: 青蛙的约会

    二次联通门 : BZOJ 1477: 青蛙的约会 /* BZOJ 1477: 青蛙的约会 扩展欧几里得 列出方程, 判断一下 */ #include <iostream> #include ...