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. java——形参与实参

    看了很多的文章,稍微有一些的总结:对最基本的形参与实参有了一定的理解,虽然还是不够深入. 1.基本概念 形参:全称为"形式参数"是在定义函数名和函数体的时候使用的参数,目的是用来接 ...

  2. union 和struct大小计算

    一.字节对齐 现代计算机的内存空间是按照字节(byte)来划分的,字节对齐的意思是在给特定变量类型分配内存空间的时候,变量的内存地址是它本身变量类型大小的整数倍.比如,给int类型的变量a分配地址空间 ...

  3. 图像转化成TFrecords格式并回转

    import os import tensorflow as tf from PIL import Image import numpy as np cat_image_path='D:/软件/pyc ...

  4. Java Script--------问题错误解决意外的终止输入Uncaught SyntaxError: Unexpected end of input解决办法

    错误信息: Uncaught SyntaxError: Unexpected end of input 错误原因: 一般是成对的符号只出现了单只,比如说“”,‘’,{},[]. 解决办法:检查符号是否 ...

  5. django之信号

    Django中提供了“信号调度”,用于在框架执行操作时解耦.通俗来讲,就是一些动作发生的时候,信号允许特定的发送者去提醒一些接受者. 1.Django内置信号 Model signals     pr ...

  6. vs-code 基础设置

    汉化设置: 最新版的vscode 汉化需要两步 1 ctrl+shift+p   在顶部输入框中输入 language 后选择  configure Display Language  后进入 第二张 ...

  7. 自建 yum 源

    生产环境需要大规模的安装部署rpm包,每次安装,更新,都需要上传,安装,比较麻烦,可以在生产环境中自建一个yum源. 1.http安装 yum -y install httpd systemctl s ...

  8. Python 死锁现象

    import time from threading import Thread,Lock,RLock def f1(locA,locB): locA.acquire() print('f1>& ...

  9. 网易2019校招内推编程题-俄罗斯方块-C++实现

    [编程题] 俄罗斯方块 时间限制:1秒 空间限制:262144K 小易有一个古老的游戏机,上面有着经典的游戏俄罗斯方块.因为它比较古老,所以规则和一般的俄罗斯方块不同.荧幕上一共有 n 列,每次都会有 ...

  10. vue 打印功能

    printContent (e) { let subOutputRankPrint = document.getElementById('subOutputRank-print') console.l ...