如何解决这个js嵌套数组问题:给定一个单词和一个字符串骨架数组,返回一个可能的骨架单词匹配数组
在这工作了很多小时之后,我不知道如何解决以下问题。请提供解决方案并提供解释或建议以改进我的解决方案。
/* 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;
}
after working at this for many hours, I am lost at how to solve the following problem. Please offer solutions with explanations or suggestions to improve my solution.
/* 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您很接近,但
如果有任何字母不匹配或该字母是
-
,则会取消骨架资格。因此,这将取消任何不完全匹配的单词的资格。您需要使用&&
- 仅当字母不匹配且字母不是-
时才取消资格。或者,重构为看起来更好:
数组方法通常是一种比命令式基于索引的
for
循环更简洁的好方法。如果您实际上并不关心索引,只关心正在迭代的值,那么您通常可以完全放弃for (let i =
构造,并使用数组方法或 for..of.You're close, but
will disqualify a skeleton if any letter doesn't match or the letter is a
-
. So this'll disqualify any words that aren't exact matches. You want&&
instead - disqualify only if the letter doesn't match and the letter isn't a-
.Or, refactored to look nicer:
Array methods are often a nice way to make code much cleaner than imperative index-based
for
loops. If you don't actually care about the index, only the value being iterated over, you can often ditch thefor (let i =
construct entirely, and either use an array method or for..of.