LeetCode - 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.
只需检测和要搜索单词长度一样的单词即可,所以我们用的数据结构就是根据单词的长度来分,把长度相同相同的单词放到一起,这样就可以减少搜索量。那么对于和要搜索单词进行比较的单词,由于已经保证了长度相等,我们直接进行逐个字符比较即可,用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的更多相关文章
- [LeetCode] Implement Magic Dictionary 实现神奇字典
Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...
- LC 676. Implement Magic Dictionary
Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...
- Week6 - 676.Implement Magic Dictionary
Week6 - 676.Implement Magic Dictionary Implement a magic directory with buildDict, and search method ...
- LeetCode 676. Implement Magic Dictionary实现一个魔法字典 (C++/Java)
题目: Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll ...
- [LeetCode] 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 ...
- [Swift]LeetCode676. 实现一个魔法字典 | Implement Magic Dictionary
Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...
- 676. Implement Magic Dictionary
Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...
- [LeetCode] Implement Trie (Prefix Tree) 实现字典树(前缀树)
Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs ar ...
随机推荐
- 复制程序到notepad++编辑器出现乱码的解决方法
1.不从别的编辑器打开的文件中直接复制代码到notepad++打开的文件中,也不从notepad++打开的文件中复制到别的编辑器打开的文件中.但是确实想移植一些代码怎么办呢?具体方法:在别的编译器编辑 ...
- linux 普通用户授权root相关权限
先查看当前用户(test)是否有特权 [test@web01 ~]$ sudo -l We trust you have received the usual lecture from the loc ...
- HIVE中IN的坑
问题:为什么HIVE中用了 NOT IN,结果集没了? 注:这个是原创,转载请注明,谢谢!直接进实验室>> > select * from a;OK1 a12 a23 a3Time ...
- websocket的属性readyState
webSocket的readyState属性用来定义连接状态,该属性的值有下面几种: 0 :对应常量CONNECTING (numeric value 0), 正在建立连接连接,还没有完成.The c ...
- python web架构初步认识
---恢复内容开始--- #主入口,Python解释器从这开始执行:if __name__ == '__main__': run() 内部执行过程: #引用socket模块 import socket ...
- puthon文件头
#!/usr/bin/u/ubv/a python # -*- coding:utf-8 -*-
- php:数组与json数据相互转换
1.数组转json $json=json_encode(数组名) 数组转json字符串 2,json转数组 $arr=json_decode(json字符串,[true]) 不加true第一次转直接转 ...
- head语法
head 与 tail 就像它的名字一样的浅显易懂,它是用来显示开头或结尾某个数量的文字区块,head 用来显示档案的开头至标准输出中,而 tail 想当然尔就是看档案的结尾.1.命令格式:head ...
- xpath | 计算两个节点集
url = li.xpath("./div/div[2]/a/@href | ./div/div[2]/div[2]/a/@href").extract_first()
- 初学node遇到的问题(慢慢补充)
一.看到菜鸟教程的Web模块运行client.js的时候遇到报错: E:\node\server>node client.js events.js:72throw er; // Unhandle ...