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.

这道题让我们设计一种神奇字典的数据结构,里面有一些单词,实现的功能是当我们搜索一个单词,只有存在和这个单词只有一个位置上的字符不相同的才能返回true,否则就返回false,注意完全相同也是返回false,必须要有一个字符不同。博主首先想到了One Edit Distance那道题,只不过这道题的两个单词之间长度必须相等。所以只需检测和要搜索单词长度一样的单词即可,所以我们用的数据结构就是根据单词的长度来分,把长度相同相同的单词放到一起,这样就可以减少搜索量。那么对于和要搜索单词进行比较的单词,由于已经保证了长度相等,我们直接进行逐个字符比较即可,用cnt表示不同字符的个数,初始化为0。如果当前遍历到的字符相等,则continue;如果当前遍历到的字符不相同,并且此时cnt已经为1了,则break,否则cnt就自增1。退出循环后,我们检测是否所有字符都比较完了且cnt为1,是的话则返回true,否则就是跟下一个词比较。如果所有词都比较完了,则返回false,参见代码如下:

解法一:

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 = , i = ;
for (; i < word.size(); ++i) {
if (word[i] == str[i]) continue;
if (word[i] != str[i] && cnt == ) break;
++cnt;
}
if (i == word.size() && cnt == ) return true;
}
return false;
} private:
unordered_map<int, vector<string>> m;
};

下面这种解法实际上是用到了前缀树中的search的思路,但是我们又没有整个用到prefix tree,博主感觉那样写法略复杂,其实我们只需要借鉴一下search方法就行了。我们首先将所有的单词都放到一个集合中,然后在search函数中,我们遍历要搜索的单词的每个字符,然后把每个字符都用a-z中的字符替换一下,形成一个新词,当然遇到本身要跳过。然后在集合中看是否存在,存在的话就返回true。记得换完一圈字符后要换回去,不然就不满足只改变一个字符的条件了,参见代码如下:

解法二:

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 = ; 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;
};

类似题目:

Implement Trie (Prefix Tree)

参考资料:

https://discuss.leetcode.com/topic/103004/c-clean-code

https://discuss.leetcode.com/topic/102992/easy-14-lines-java-solution-hashmap

LeetCode All in One 题目讲解汇总(持续更新中...)

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

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

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

  2. LeetCode - Implement Magic Dictionary

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

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

    Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs ar ...

  4. LC 676. Implement Magic Dictionary

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

  5. Week6 - 676.Implement Magic Dictionary

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

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

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

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

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

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

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

  9. 676. Implement Magic Dictionary

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

随机推荐

  1. 0x00-Kali Linux 系列入门篇

    Kali Linux介绍篇 Kali Linux 官网:https://www.kali.org/ Kali Linux 前身是著名渗透测试系统BackTrack ,是一个基于 Debian 的 Li ...

  2. postman简单教程-环境变量,全局变量的设置及作用

    讲postman环境变量设置之前,先讲一个小插曲,环境变量.全局变量的区别在于Globals,只能用一组,而Environmen可以设置多组,所以我更喜欢设置环境变量 1.环境变量-Environme ...

  3. Matlab绘图基础——用print函数保存图片(Print figure or save to file)

    print(figure_handle,'formats','-rnumber','filename')  %将图形保存为png格式,分辨率为number的(默认为72),最好指定的分辨率大一点,否则 ...

  4. C++ STL常用容器基本用法汇总

    1.vector 包含头文件#include<vector> 使用命名域using namespace std 定义元素类型为T的vector vector<T> vec 增: ...

  5. 201621123043 《Java程序设计》第6周学习总结

    1.1 面向对象学习暂告一段落,请使用思维导图,以封装.继承.多态为核心概念画一张思维导图或相关笔记,对面向对象思想进行一个总结. 注1:关键词与内容不求多,但概念之间的联系要清晰,内容覆盖面向对象的 ...

  6. Python IDE Spyder的简单介绍

    最近深度学习发展非常迅猛,大有一统江湖的趋势.经过一段时间学习,发现自己对这种神奇的玄学非常感兴趣,希望能够进一步的研究.而这种研究性学科单纯地看论文比较难以明白,所以希望能够跟进大牛们写的代码深入学 ...

  7. Python upper()方法

    描述 Python upper() 方法将字符串中的小写字母转为大写字母. 语法 upper()方法语法: str.upper() 参数 NA. 返回值 返回小写字母转为大写字母的字符串. 实例 以下 ...

  8. Tornado 用户身份验证框架

    1.安全cookie机制 import tornado.web session_id = 1 class MainHandler(tornado.web.RequestHandler): def ge ...

  9. 前端面试之angular JS

    1. angular的数据绑定采用什么机制?详述原理 angularjs的双向数据绑定,采用脏检查(dirty-checking)机制.ng只有在指定事件触发后,才进入 $digest cycle : ...

  10. EMC CX4-480服务器raid磁盘数据恢复案例

    [用户信息]上海某公司 [故障描述]需要进行数据恢复的设备是一台EMC CX4的存储服务器,因为硬盘出现故障导致整个存储阵列瘫痪.整个LUN是由7块1TB的硬盘组成的RAID 5.但服务器共有10块硬 ...