没有进入if块



const words = [
"a",
"alien",
"born",
"less",
"lien",
"never",
"nevertheless",
"new",
"newborn",
"the",
"zebra",
"zebra",
];
let compoundArr = [];
let memo = new Map();
setFixes = () => {
for (let word of words) {
for (let i = 1; i < word.length; i++) {
const prefix = word.substring(0, i);
const suffix = word.substring(i);
if (memo.get(prefix)) return;
else {
if (words.includes(prefix)) memo.set(prefix, true);
}
if (memo.get(suffix)) return;
else {
if (words.includes(suffix)) memo.set(suffix, true);
}
}
}
};
findCompound = () => {
setFixes();
for (let word of words) {
for (let i = 1; i < word.length; i++) {
const prefix = word.substring(0, i);
const suffix = word.substring(i);
if (memo.get(prefix) === true && memo.get(suffix) === true) {
compoundArr.push(word);
}
}
}
return compoundArr;
};
findCompound();
console.log(compoundArr);

嗨,我在这里使用映射来存储前缀和后缀,以避免搜索相同的字符和更大的部分,如果可能的话。然而,我注意到它从不从存储的值中读取,它跳过了这个"if (memo.get(prefix)) return"one_answers"if (memo.get(suffix)) return"部分,并再次移动到单词数组中搜索。我们如何解决这个问题?

以下是一些问题和备注:

  • 当执行return时,函数结束,因此一旦发现前缀/后缀已经在Map中,函数停止任何进一步的处理。而不是return,您只需跳过仅为特定字符串写入Map的部分。

  • 由于您的代码只使用和检查Map中的值true,因此您可以只使用Set。

  • 你的函数变量隐式声明为全局变量。最好使用const来定义它们,或者使用function语句。

  • 使用函数参数,以便清楚哪些变量可能被它们使用。如果函数创建了一个数据结构,那么让它返回它(而不是改变一个全局变量)。让调用者将函数结果赋值给自己的变量(可能是全局变量)。

  • 为了避免重复扫描words数组,最好将该数组转换为一次Set,然后使用has而不是includes

  • 由于复合词可能由作为前缀和后缀出现多次的单词组成,因此您希望将复合词列表也收集为一个Set,以避免重复。你可以把它变成一个数组作为最后一步。

const setFixes = (words) => {
const wordSet = new Set(words); // To speed up look-up
const fixes = new Set(); // Instead of Map
for (const word of words) {
for (let i = 1; i < word.length; i++) {
const prefix = word.substring(0, i);
const suffix = word.substring(i);
// Don't exit the function here -- just skip
if (wordSet.has(prefix)) fixes.add(prefix);
if (wordSet.has(suffix)) fixes.add(suffix);
}
}
return fixes; // Return it
};
const findCompound = (words) => {
const fixes = setFixes(words);
const compounds = new Set; // Local; and avoid duplicates
for (const word of words) {
for (let i = 1; i < word.length; i++) {
const prefix = word.substring(0, i);
const suffix = word.substring(i);
if (fixes.has(prefix) && fixes.has(suffix)) {
compounds.add(word);
}
}
}
return [...compounds]; // Turn to array
};
const words = ["a","alien","born","less","lien","never","nevertheless","new","newborn","the","zebra","zebra",];
const compoundArr = findCompound(words);
console.log(compoundArr);

相关内容

  • 没有找到相关文章

最新更新