题目
题目来源:力扣(LeetCode)
设计一个使用单词列表进行初始化的数据结构,单词列表中的单词 互不相同 。 如果给出一个单词,请判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。
实现 MagicDictionary 类:
MagicDictionary() 初始化对象
void buildDict(String[] dictionary) 使用字符串数组 dictionary 设定该数据结构,dictionary 中的字符串互不相同
bool search(String searchWord) 给定一个字符串 searchWord ,判定能否只将字符串中 一个 字母换成另一个字母,使得所形成的新字符串能够与字典中的任一字符串匹配。如果可以,返回 true ;否则,返回 false 。
示例:
输入
[“MagicDictionary”, “buildDict”, “search”, “search”, “search”, “search”]
[[], [[“hello”, “leetcode”]], [“hello”], [“hhllo”], [“hell”], [“leetcoded”]]
输出
[null, null, false, true, false, false]
解释
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict([“hello”, “leetcode”]);
magicDictionary.search(“hello”); // 返回 False
magicDictionary.search(“hhllo”); // 将第二个 ‘h’ 替换为 ‘e’ 可以匹配 “hello” ,所以返回 True
magicDictionary.search(“hell”); // 返回 False
magicDictionary.search(“leetcoded”); // 返回 False
function Trie() {
this.map = {};
this.isEnd = false;
}
/**
* Initialize your data structure here.
*/
var MagicDictionary = function () {
this.root = [];
};
/**
* @param {string[]} dictionary
* @return {void}
*/
MagicDictionary.prototype.buildDict = function (dictionary) {
dictionary.forEach((item) => {
let tmp = new Trie();
this.insert(tmp, item);
this.root.push(tmp);
});
};
MagicDictionary.prototype.insert = function (node, word) {
for (let i = 0; i < word.length; i++) {
node.map[word[i]] = node.map[word[i]] || new Trie();
node = node.map[word[i]];
}
node.isEnd = true;
};
/**
* @param {string} searchWord
* @return {boolean}
*/
MagicDictionary.prototype.search = function (searchWord) {
return this.root.reduce((total, item) => {
return total || this.searchDfs(item, searchWord);
}, false);
};
MagicDictionary.prototype.searchDfs = function (node, searchWord) {
let flag = false;
for (let i = 0; i < searchWord.length; i++) {
if (node.map[searchWord[i]]) {
node = node.map[searchWord[i]];
} else if (!flag) {
flag = true;
let keys = Object.keys(node.map);
return keys.reduce((total, item) => {
return total || this.dfs(node.map[item], searchWord.slice(i + 1));
}, false);
} else {
return false;
}
}
return false;
};
MagicDictionary.prototype.dfs = function (node, word) {
for (let i = 0; i < word.length; i++) {
if (node.map[word[i]]) {
node = node.map[word[i]];
} else {
return false;
}
}
return node.isEnd;
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* var obj = new MagicDictionary()
* obj.buildDict(dictionary)
* var param_2 = obj.search(searchWord)
*/