实现一个带有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 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class MagicDictionary {
unordered_set<string> origin;
unordered_set<int> len;
string temp;
int i;
char ch;
public:
/** Initialize your data structure here. */
MagicDictionary() {}
/** Build a dictionary through a list of words */
void buildDict(vector<string> 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;
}
};