[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:
- You may assume that all the inputs are consist of lowercase letters
a-z
. - For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest.
- 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 实现神奇字典的更多相关文章
- [LeetCode] Implement Magic Dictionary 实现神奇字典
Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...
- LeetCode 676. Implement Magic Dictionary实现一个魔法字典 (C++/Java)
题目: Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll ...
- Week6 - 676.Implement Magic Dictionary
Week6 - 676.Implement Magic Dictionary Implement a magic directory with buildDict, and search method ...
- LC 676. Implement Magic Dictionary
Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...
- 【LeetCode】676. Implement Magic Dictionary 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典 汉明间距 日期 题目地址:https://le ...
- 676. Implement Magic Dictionary
Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...
- [LeetCode] 208. Implement Trie (Prefix Tree) 实现字典树(前缀树)
Implement a trie with insert, search, and startsWith methods. Example: Trie trie = new Trie(); trie. ...
- [Swift]LeetCode676. 实现一个魔法字典 | Implement Magic Dictionary
Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...
- LeetCode - Implement Magic Dictionary
Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...
随机推荐
- python开发应用之-时间戳
golang 获取时间戳用time.Now().Unix(),格式化时间用t.Format,解析时间用time.Parse package main import ( "fmt" ...
- JQuery系列(4) - AJAX方法
jQuery对象上面还定义了Ajax方法($.ajax()),用来处理Ajax操作.调用该方法后,浏览器就会向服务器发出一个HTTP请求. $.ajax方法 $.ajax()的用法主要有两种. $.a ...
- linux中>/dev/null 2>&1和2>&1 > /dev/null
转载:https://www.cnblogs.com/520playboy/p/6275022.html 背景 我们经常能在shell脚本中发现>/dev/null 2>&1这样的 ...
- mybatis的注意事项一
在UserMapper.xml文件中写resultType="cn.smbms.dao.pojo.User"返回类型的全路径是不是很长,而且也比较不美观:不便于后期项目的维护. 解 ...
- web自动化测试-模块驱动测试实例和数据驱动测试实例
一.模块驱动测试实例 把登录和退出统一封装在login类中,若把login类单独放在一个文件中,就可以给任一测试脚本调用,这里就跟测试脚本放一起 from selenium import webdri ...
- Oracle EXPDP导出数据
Oracle expdp导出表数据(带条件): expdp student/123456@orcl dumpfile=student_1.dmp logfile=student_1.log table ...
- Otsu 类间方差法
又称最大类间方差法.是由日本学者大津(Nobuyuki Otsu)于1979年提出的[1],是一种自适合于双峰情况的自动求取阈值的方法.又叫大津法,简称Otsu. 算法提出初衷是是按图像的灰度特性 ...
- WinDbg常用命令系列---清屏
.cls (Clear Screen) .cls命令清除调试器命令窗口显示. .cls 环境: 模式 用户模式下,内核模式 目标 实时. 崩溃转储 平台 全部 清屏前 清屏后
- 权限管理(chown、chgrp、umask)
对于文件或目录的权限的修改,只能管理员和文件的所有者拥有此权限,但是对于文件或目录的的所有者的更改,只有管理员拥有此权限(虽然普通用户创建的文件或目录,用户也不能修改文件或目录的所有者). 1.cho ...
- Why We Changed YugaByte DB Licensing to 100% Open Source
转自:https://blog.yugabyte.com/why-we-changed-yugabyte-db-licensing-to-100-open-source/ 主要说明了YugaByte ...