[676] 实现一个魔法字典
暴力数组遍历
details
class MagicDictionary {
constructor() {
this.dictionary = [];
}
// Build the dictionary from a list of words
buildDict(words) {
this.dictionary = words;
}
// Search for a word that can be formed by modifying exactly one letter
search(word) {
for (let dictWord of this.dictionary) {
if (this.isMagicMatch(word, dictWord)) {
return true;
}
}
return false;
}
// Helper function to check if two words match by changing exactly one letter
isMagicMatch(word1, word2) {
if (word1.length !== word2.length) {
return false;
}
let diffCount = 0;
for (let i = 0; i < word1.length; i++) {
if (word1[i] !== word2[i]) {
diffCount++;
}
if (diffCount > 1) {
return false;
}
}
return diffCount === 1;
}
}