例如,如果空格是分隔符,
var str = "ab cde fgh ij klmn opq";
我想得到
var result = [
["ab", "cde", "fgh", "ij", "klmn", "opq"],
["ab", "cde", "fgh", "ij", "klmn opq"],
["ab", "cde", "fgh", "ij klmn opq"],
//...
["ab", "cde", "fgh ij", "klmn opq"],
["ab", "cde", "fgh ij klmn", "opq"],
//...
["ab cde", "fgh", "ij", "klmn", "opq"],
["ab cde", "fgh", "ij", "klmn opq"],
//...
["ab cde", "fgh ij", "klmn opq"],
["ab cde", "fgh ij klmn", "opq"],
//...
["ab cde fgh ij klmn", "opq"]
];
解决此类问题的有效方法是什么?
我自己的尝试仅解决了部分问题:
"ab"
,然后得到"ab" + ["cde", "fgh", "ij", "klmn", "opq"], ["cde", "fgh", "ij", "klmn opq"]
..."ab cde"
,然后得到"ab cde" + ["fgh", "ij", "klmn", "opq"], ["fgh", "ij", "klmn opq"]
......等等。但是这种方法不允许收集所有可能的序列(如上例所示)。
您可以递归地构建序列。只需将第一个单词加入到其余序列的每个序列构建中,或将其附加为新单词。尽管此解决方案的调用堆栈溢出存在一些问题。
但是您可以看到基本思想。
const str = 'ab cde fgh ij';
function getAllSequences(words) {
if (words.length === 1) {
return [words];
}
const [first, ...rest] = words;
const sequences = getAllSequences(rest);
return sequences.reduce((sequences, sequence) => {
const withFirstConnected = [].concat(first + ' ' + sequence[0], sequence.slice(1));
const withFirstUnshift = [].concat(first, sequence);
return sequences.concat([withFirstConnected], [withFirstUnshift]);
}, []);
}
console.log(getAllSequences(str.split(' ')));
另一个没有递归的版本,类似的方法,但是添加了最后一个单词而不是第一个单词。
function getAllSequences(words) {
return words.reduce(addWordToSequences, [[]]);
}
function addWordToSequences(sequences, word) {
return sequences.reduce((sequences, sequence) => {
if (sequence.length === 0) {
return [[word]];
}
const last = sequence[sequence.length - 1];
const front = sequence.slice(0, sequence.length - 1);
const withWordJoined = front.concat(last + ' ' + word);
return sequences.concat([withWordJoined], [sequence.concat(word)]);
}, []);
}
console.log(getAllSequences('something mdd ala ba'.split(' ')))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句