使用 JavaScript 检查字符串是否是数组中字符串的组合
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/9 10:20:17
我们需要编写一个 JavaScript 函数,该函数将字符串数组作为第一个参数,将字符串作为第二个参数。
该函数应检查第二个参数指定的字符串是否可以通过以任何可能的方式组合数组的字符串来形成。
例如 − 如果输入数组是 −
const arr = ["for","car","keys","forth"];
并且字符串是 −
const str = "forthcarkeys";
那么输出应该为 true,因为该字符串是数组中索引 3、1 和 2 处的元素的组合。
示例
其代码为 −
const arr = ["for","car","keys","forth"];
const str = "forthcarkeys";
const checkPossibility = (str = '', arr = []) => {
let possibilities = arr.reduce(function (r, a) {
let p = str.indexOf(a);
while (p !== −1) {
r.push({ word: a, position: p });
p = str.indexOf(a, p + 1);
}
return r;
}, []);
const findRecursively = (i, t) => {
let s = t.slice(), j;
if (i === possibilities.length) {
return !t.join('');
}
if (possibilities[i].word.split('').every(function (c, j) {
return
s[j + possibilities[i].position] !== ''; })) {
for (j = 0; j < possibilities[i].word.length; j++) {
s[j + possibilities[i].position] = '';
}
}
return findRecursively(i + 1, s) || findRecursively(i + 1, t);
}
return findRecursively(0, str.split(''));
};
console.log(checkPossibility(str, arr));
输出
控制台中的输出将是 −
true
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

