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. react native进一步学习(NavigatorIOS 学习)

    特别申明:本人代码不作为任何商业的用途,只是个人学习的一些心得,为了使得后来的更多的程序员少走一些弯路.*(如若侵犯你的版权还望见谅)*. 开发工具:WebStorm,xcode 1. rn的创建的时 ...

  2. 关于dom&bom

    javascript 有三部分构成,ECMAScript,DOM和BOM,根据宿主(浏览器)的不同,具体的表现形式也不尽相同,ie和其他的浏览器风格迥异. 1. DOM 是 W3C的标准:[所有浏览器 ...

  3. AsyncTask 进行耗时操作和UI 更新

    相信各位对 AsyncTask 不会陌生,虽然它有如下弊端: 1. 如果在activiy内部new 一个AsyncTask, 横竖屏切换生成一个新的activity,等结果返回时,处理不好容易出现NP ...

  4. Codeforces Round #479 (Div. 3) F. Consecutive Subsequence (简单dp)

    题目:https://codeforces.com/problemset/problem/977/F 题意:一个序列,求最长单调递增子序列,但是有一个要求是中间差值都是1 思路:dp,O(n)复杂度, ...

  5. Oracle学习DayTwo

    一.创建表和管理表 1.表名和列名的命名规则 必须以字母开头必须在 1–30 个字符之间必须只能包含 A–Z, a–z, 0–9, _, $, 和 #必须不能和用户定义的其他对象重名必须不能是Orac ...

  6. Linux:Fedora系统的安装

    新的一周,新的一天又来了!话不多说我们直接进入今天的系统安装吧!这次是Linux系统的第八期了,这款系统是可以当做家庭用途使用,非常强大的一款开发源操作系统. 安装Fedora系统 系统映像文件下载 ...

  7. io 的一些简单说明及使用

    io 流简述: i->inputStream(输入流) o->outputStream  (输出流) IO流简单来说就是Input和Output流,IO流主要是用来处理设备之间的数据传输, ...

  8. 从网络上获取图片,并写入excel文件

    package com.weChat.utils; import com.manage.utils.DateUtil;import com.manage.utils.MD5Util;import or ...

  9. 修改权限linux

    1.更改目录所有者命令:chown -R 用户名称 目录名称2.更改目录权限命令:chmod -R 755 目录名称 nginx在不同目录下需要给与全部权限才可以

  10. python中的 uuid 模块使用示例

    此模块提供不可变的 UUID 对象 (类 uuid) 和函数uuid1().uuid3().uuid4().uuid5(), 用于生成在 RFC 4122 中指定版本1.3.4和5UUIDs .如果你 ...