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.

只需检测和要搜索单词长度一样的单词即可,所以我们用的数据结构就是根据单词的长度来分,把长度相同相同的单词放到一起,这样就可以减少搜索量。那么对于和要搜索单词进行比较的单词,由于已经保证了长度相等,我们直接进行逐个字符比较即可,用cnt表示不同字符的个数,初始化为0。如果当前遍历到的字符相等,则continue;如果当前遍历到的字符不相同,并且此时cnt已经为1了,则break,否则cnt就自增1。退出循环后,我们检测是否所有字符都比较完了且cnt为1,是的话则返回true,否则就是跟下一个词比较。如果所有词都比较完了,则返回false,参见代码如下:

class MagicDictionary {

    private HashMap<Integer, List<String>> map;

    /** Initialize your data structure here. */
public MagicDictionary() {
map = new HashMap<Integer, List<String>>();
} /** Build a dictionary through a list of words */
public void buildDict(String[] dict) {
for(String str : dict){
int len = str.length();
if(map.containsKey(len)){
map.get(len).add(str);
}
else{
List<String> list = new ArrayList<>();
list.add(str);
map.put(len, list);
}
}
} /** 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) {
if(word == null || word.length() == 0){
return false;
}
int len = word.length();
if(map.containsKey(len)){
List<String> list = map.get(len);
for(String str : list){
if(hasExactOneDifference (str, word)){
return true;
}
}
}
return false;
} private boolean hasExactOneDifference(String str1, String str2){
int cnt = 0;
for(int i = 0; i< str1.length(); i++){
if(str1.charAt(i) != str2.charAt(i)){
if(cnt == 1){
return false;
}
else{
cnt++;
}
}
}
if(cnt == 1){
return true;
}
return false; }
} /**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary obj = new MagicDictionary();
* obj.buildDict(dict);
* boolean param_2 = obj.search(word);
*/

LeetCode - 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. LC 676. Implement Magic Dictionary

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

  3. Week6 - 676.Implement Magic Dictionary

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

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

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

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

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

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

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

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

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

  8. 676. Implement Magic Dictionary

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

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

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

随机推荐

  1. SQL-54 查找排除当前最大、最小salary之后的员工的平均工资avg_salary。

    题目描述 查找排除当前最大.最小salary之后的员工的平均工资avg_salary.CREATE TABLE `salaries` ( `emp_no` int(11) NOT NULL,`sala ...

  2. python-之-深浅拷贝二(元组)

    元组比较特殊 1.----元组本身为不可变类型 import copy v1 = (1, 2, 3, 4) v2 = copy.copy(v1) print(id(v1), id(v2)) v3 = ...

  3. 关于“load”方法

    load是一个方法,在程序文件中,只有ruby遇到它的时候才会执行.Ruby不会搜索整个文件去执行load命令.也就是说,当Ruby解释器遇到它的时候,它才会去寻找它要加载的文件.这意味着需要加载的文 ...

  4. MySQL从本地向数据库导入数据

    本文来自:https://www.cnblogs.com/lettuce-u/p/10715795.html(自己收藏看) 在localhost中准备好了一个test数据库和一个pet表: mysql ...

  5. QT_REQUIER_CONFIG

    在qglobal.h中,定义了很多宏.下面这个QT_REQUIER_CONFIG,展开成: #define QT_REQUIRE_CONFIG(feature) Q_STATIC_ASSERT_X(Q ...

  6. [转载] java并发编程:Lock(线程锁)

    作者:海子 原文链接: http://www.cnblogs.com/dolphin0520/p/3923167.html 出处:http://www.cnblogs.com/dolphin0520/ ...

  7. JS 删除Array对象中的元素。

    var idTemp=new Array(); var nameTemp = new Array(); nameTemp.splice($.inArray(“1”, nameTemp),1); idT ...

  8. iptables-save命令

    [root@localhost ~]# iptables-save -t filter > iptables.bak [root@localhost ~]# cat iptables.bak # ...

  9. 修改XAMPP的默认根目录

    XAMPP安装完成后,默认根目录路径是C:\xampp\htdocs,如果想要在服务器下运行文件就必须把该文件copy到C:\xampp\htdocs下.超麻烦不说,公司代码总不能放进去运行吧...所 ...

  10. SQL Server tempdb 数据库位置迁移

    SQL Server tempdb 数据库位置迁移 --查看物理位置 SELECT name, physical_name FROM sys.master_files WHERE database_i ...