使用JavaScript检查字符串是否是数组中字符串的组合
我们需要编写一个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