珠海 网站设计,百度搜索引擎的网址是,wordpress加接入又拍云,呼和浩特网站开发1. 题目
实现一个带有buildDict, 以及 search方法的魔法字典。
对于buildDict方法#xff0c;你将被给定一串不重复的单词来构建一个字典。
对于search方法#xff0c;你将被给定一个单词#xff0c;并且判定能否只将这个单词中一个字母换成另一个字母#xff0c;使得所…1. 题目
实现一个带有buildDict, 以及 search方法的魔法字典。
对于buildDict方法你将被给定一串不重复的单词来构建一个字典。
对于search方法你将被给定一个单词并且判定能否只将这个单词中一个字母换成另一个字母使得所形成的新单词存在于你构建的字典中。
示例 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注意: 你可以假设所有输入都是小写字母 a-z。 为了便于竞赛测试所用的数据量很小。你可以在竞赛结束后考虑更高效的算法。 请记住重置MagicDictionary类中声明的类变量因为静态/类变量会在多个测试用例中保留。
来源力扣LeetCode 链接https://leetcode-cn.com/problems/implement-magic-dictionary 著作权归领扣网络所有。商业转载请联系官方授权非商业转载请注明出处。
2. 解题
建立原始字典的哈希表以及单词长度的记录表查找时长度必须相等且变形词在哈希表中且变形词不为原词
class MagicDictionary {unordered_setstring origin;unordered_setint len;string temp;int i;char ch;
public:/** Initialize your data structure here. */MagicDictionary() {}/** Build a dictionary through a list of words */void buildDict(vectorstring dict) {for(string word : dict) {origin.insert(word);len.insert(word.length());}}bool search(string word) {if(!len.count(word.length()))return false;for(i 0; i word.size(); i){temp word;for(ch a; ch z; ch){temp[i] ch;if(origin.count(temp) temp ! word)return true;} }return false;}
};