来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/implement-magic-dictionary 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
设计一个使用单词列表进行初始化的数据结构,单词列表中的单词 互不相同 。 如果给出一个单词,请判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。
实现 MagicDictionary 类:
MagicDictionary() 初始化对象
void buildDict(String[] dictionary) 使用字符串数组 dictionary 设定该数据结构,dictionary 中的字符串互不相同
bool search(String searchWord) 给定一个字符串 searchWord ,判定能否只将字符串中 一个 字母换成另一个字母,使得所形成的新字符串能够与字典中的任一字符串匹配。如果可以,返回 true ;否则,返回 false 。
解答
var MagicDictionary = function() {this.dict = [];};/*** @param {string[]} dictionary* @return {void}*/MagicDictionary.prototype.buildDict = function(dictionary) {this.dict = dictionary;};const compare = (source, target, len) => {let count = 0;for (let i = 0; i < len; i++) {if (source[i] !== target[i]) {++count;}}return count;}/*** @param {string} searchWord* @return {boolean}*/MagicDictionary.prototype.search = function(searchWord) {const sLength = searchWord.length;this.dict.forEach(str => {if (str.length === sLength) {return compare(str, searchWord, sLength);}})let i = 0,len = this.dict.length;while (i < len) {const str = this.dict[i];if (str.length === sLength) {let count = compare(str, searchWord, sLength);if (count === 1) {return true;}}++i;}return false;};/*** Your MagicDictionary object will be instantiated and called as such:* var obj = new MagicDictionary()* obj.buildDict(dictionary)* var param_2 = obj.search(searchWord)*/
