如何解决这个 js 嵌套数组问题:给定一个单词和一个字符串骨架数组 return 一个可能的骨架词匹配数组

How to solve this js nested arrays problems: given a word and an array of string skeletons return an array of possible skeleton-word matches

在这上面工作了很多小时后,我不知道如何解决以下问题。请提供带有解释或建议的解决方案以改进我的解决方案。

/* instructions
Given a word and an array of string skeletons, return an array of all of the skeletons that could be turned into the word by replacing the '-' with letters. If there are no possible matches return an empty string example: given the word 'hello' 'he---' would 
be a match, 'h--l' or 'g-llo' would not be a match */

// example test case:
let word = 'hello';
let skeletons = ['h--l', 'he---', 'g-llo', 'm-llo', '--llo', 'h-l--'];

function findSkels(word, skeleton){
let goodSkels = [];
skeleton = skeletons.filter(w => w.length === word.length);
console.log(skeletons)
  for(let sw = 0; sw < skeletons.length; sw++){
    let possibleMatch = true;
    for(let letter = 0; letter < word.length; letter++){
      if(word[letter] !== skeletons[sw][letter] || skeletons[sw][letter] == '-'){
        possibleMatch = false
      }
    }
    if(possibleMatch){
      goodSkels.push(skeletons[sw])
    }
  } 
    return goodSkels;
}

你很接近,但是

if (word[letter] !== skeletons[sw][letter] || skeletons[sw][letter] == '-') {
  possibleMatch = false
}

如果任何字母不匹配 字母是 -,骨架将被取消资格。因此,这将取消任何不完全匹配的词的资格。你想要 && - 只有当字母不匹配 字母不是 -.

时才取消资格

/* instructions
Given a word and an array of string skeletons, return an array of all of the skeletons that could be turned into the word by replacing the '-' with letters. If there are no possible matches return an empty string example: given the word 'hello' 'he---' would 
be a match, 'h--l' or 'g-llo' would not be a match */

// example test case:
let word = 'hello';
let skeletons = ['h--l', 'he---', 'g-llo', 'm-llo', '--llo', 'h-l--'];

function findSkels(word, skeleton) {
  let goodSkels = [];
  skeleton = skeletons.filter(w => w.length === word.length);
  for (let sw = 0; sw < skeletons.length; sw++) {
    let possibleMatch = true;
    for (let letter = 0; letter < word.length; letter++) {
      if (word[letter] !== skeletons[sw][letter] && skeletons[sw][letter] !== '-') {
        possibleMatch = false
      }
    }
    if (possibleMatch) {
      goodSkels.push(skeletons[sw])
    }
  }
  return goodSkels;
}
console.log(findSkels(word, skeletons));

或者,重构以看起来更好:

const word = 'hello';
const skeletons = ['h--l', 'he---', 'g-llo', 'm-llo', '--llo', 'h-l--'];

const findSkels = (word, skeletons) => skeletons
  .filter(skel => (
    skel.length === word.length &&
    [...skel].every((char, i) => char === '-' || char === word[i])
  ));
console.log(findSkels(word, skeletons));

数组方法通常是使代码比命令式 index-based for 循环更简洁的好方法。如果您实际上并不关心索引,只关心被迭代的值,您通常可以完全放弃 for (let i = 构造,并使用数组方法或 for..of.