【LeetCode】676. Implement Magic Dictionary 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/implement-magic-dictionary/description/
题目描述
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.
题目大意
判断只修改一个字符的情况下,能不能把search()输入的字符串变成buildDict()中已有的字符。
解题方法
字典
这个题可以直接使用dict完成。我们在进行buildDict()操作的时候就统计出如果修改一个字符能变成的字符串的个数。在search的过程中,我们要同样的看该word在修改一个字符的情况下能变成哪些字符串。
注意题目中说search时不能和已有的字符串完全一样,但是如果修改该词的某个字符构成的字符串能在buildDict()中出现的次数>1,那么说明可被与其不等的其他的字符串修改一个字符串构成。
顺便学习了一下python运算符的优先级:
优先级关系:or<and<not,同一优先级默认从左往右计算。
用案例进行说明:
Your input
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello","leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello","hallo","leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
Your stdout
set([u'hello', u'leetcode'])
Counter({u'leetc*de': 1, u'*ello': 1, u'lee*code': 1, u'le*tcode': 1, u'leetco*e': 1, u'h*llo': 1, u'hel*o': 1, u'l*etcode': 1, u'leetcod*': 1, u'*eetcode': 1, u'hell*': 1, u'he*lo': 1, u'leet*ode': 1})
set([u'hallo', u'hello', u'leetcode'])
Counter({u'h*llo': 2, u'leetc*de': 1, u'*ello': 1, u'hall*': 1, u'ha*lo': 1, u'le*tcode': 1, u'hal*o': 1, u'hel*o': 1, u'l*etcode': 1, u'leetco*e': 1, u'leetcod*': 1, u'lee*code': 1, u'*allo': 1, u'hell*': 1, u'he*lo': 1, u'*eetcode': 1, u'leet*ode': 1})
Your answer
[null,null,false,true,false,false]
[null,null,true,true,false,false]
代码:
class MagicDictionary(object):
def _candidate(self, word):
for i in range(len(word)):
yield word[:i] + '*' + word[i+1:]
def buildDict(self, words):
"""
Build a dictionary through a list of words
:type dict: List[str]
:rtype: void
"""
self.words = set(words)
print self.words
self.near = collections.Counter([word for word in words for word in self._candidate(word)])
print self.near
def search(self, word):
"""
Returns if there is any word in the trie that equals to the given word after modifying exactly one character
:type word: str
:rtype: bool
"""
return any(self.near[cand] > 1 or self.near[cand] == 1 and word not in self.words for cand in self._candidate(word))
# Your MagicDictionary object will be instantiated and called as such:
# obj = MagicDictionary()
# obj.buildDict(dict)
# param_2 = obj.search(word)
汉明间距
题目的意思其实就是找汉明间距为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) {
d = dict;
}
/** 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 wd : d) {
const int N = wd.size();
if (N == word.size()) {
int diff = 0;
for (int i = 0; i < N; ++i) {
if (wd[i] != word[i])
diff ++;
}
if (diff == 1)
return true;
}
}
return false;
}
private:
vector<string> d;
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary obj = new MagicDictionary();
* obj.buildDict(dict);
* bool param_2 = obj.search(word);
*/
日期
2018 年 3 月 5 日
2018 年 12 月 18 日 —— 改革开放40周年
【LeetCode】676. Implement Magic Dictionary 解题报告(Python & C++)的更多相关文章
- [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实现一个魔法字典 (C++/Java)
题目: Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll ...
- Week6 - 676.Implement Magic Dictionary
Week6 - 676.Implement Magic Dictionary Implement a magic directory with buildDict, and search method ...
- LC 676. 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】62. Unique Paths 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/unique-pa ...
- 【LeetCode】911. Online Election 解题报告(Python)
[LeetCode]911. Online Election 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ ...
- 【LeetCode】385. Mini Parser 解题报告(Python)
[LeetCode]385. Mini Parser 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/mini-parser/ ...
- 【LeetCode】376. Wiggle Subsequence 解题报告(Python)
[LeetCode]376. Wiggle Subsequence 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.c ...
随机推荐
- Oracle-like 多条件过滤以及and or用法
1.select * from file where DOC_SUBJECT not like '%测试%' and (DOC_STATUS like '待审' or DOC_STATUS li ...
- 【模板】缩点(Tarjan算法)/洛谷P3387
题目链接 https://www.luogu.com.cn/problem/P3387 题目大意 给定一个 \(n\) 个点 \(m\) 条边有向图,每个点有一个权值,求一条路径,使路径经过的点权值之 ...
- 日常Java 2021/11/3
java网络编程 网络编程是指编写运行在多个设备(计算机)的程序,这些设备都通过网络连接起来.java.net包中J2SE的APl包含有类和接口,它们提供低层次的通信细节.你可以直接使用这些类和接口, ...
- 网卡命令ifconfig
• ifconfig • service network restart • ifdown eth0 • ifdown eth0 #linux下run networkexport USER=lizhe ...
- Zookeeper【概述、安装、原理、使用】
目录 第1章 Zookeeper入门 1.1 概述 1.2 特点 1.3 数据结构 1.4应用场景 第2章 Zookeep安装 2.1 下载地址 2.2 本地模式安装 1. 安装前准备 2. 配置修改 ...
- 石墨文档Websocket百万长连接技术实践
引言 在石墨文档的部分业务中,例如文档分享.评论.幻灯片演示和文档表格跟随等场景,涉及到多客户端数据同步和服务端批量数据推送的需求,一般的 HTTP 协议无法满足服务端主动 Push 数据的场景,因此 ...
- sax方式解析XML学习笔记
原理:对文档进行顺序扫描,当扫描到文档(document)开始与结束,元素开始与结束.文档结束等地方 通知事件处理函数,由事件处理函数相应动作然后继续同样的扫描,直至文档结束. 优点:消耗资源比较少: ...
- redis入门到精通系列(七):redis高级数据类型详解(BitMaps,HyperLogLog,GEO)
高级数据类型和五种基本数据类型不同,并非新的数据结构.高级数据类型往往是用来解决一些业务场景. (一)BitMaps (1.1) BitMaps概述 在应用场景中,有一些数据只有两个属性,比如是否是学 ...
- 『与善仁』Appium基础 — 20、Appium元素定位
目录 1.by_id定位 2.by_name定位 3.by_class_name定位 4.by_xpath定位 5.by_accessibility_id定位 6.by_android_uiautom ...
- shell脚本 awk实现实时监控网卡流量
一.简介 通过第3方工具获得网卡流量,这个大家一定很清楚.其实通过脚本一样可以实现效果.下面是我个人工作中整理的数据.以下是shell脚本统计网卡流量. 现原理: cat /proc/net/dev ...