給定一個像“這是一個帶空格的搜索”這樣的字串,我想回傳該字串的所有排列,其中空格替換為破折號。例如,這是我想要的結果:
[“this-is-a-search-with-spaces”]
[“this-is-a-search-with”、“spaces”]
[“this”、“is-a-search-with-spaces”]
[ "this-is", "a-search-with-spaces"]
["this-is-a-search", "with-spaces"]
["this-is-a", "search-with-spaces"]
...等等。
我可以做到一半,但問題是它匹配 ["query1-query2", "query3"] 但不是相反的方式,如 ["query1", "query2-query3"]。
這是我當前的代碼:
const sliced = query.split(/ /g)
let permutations = []
for (let i = 1; i <= sliced.length; i ) {
let permuteArr = []
for (let j = 0; j < sliced.length; j =i) {
permuteArr.push(sliced.slice(j, j i).join("-"))
}
permutations.push(permuteArr)
}
謝謝你幫助我。
uj5u.com熱心網友回復:
這是一個產生組合的遞回生成器:
function permutations(query) {
function* iterRecur(sliced) {
if (sliced.length == 1) return yield sliced;
for (const result of iterRecur(sliced.slice(1))) {
yield [sliced[0] "-" result[0], ...result.slice(1)];
yield [sliced[0], ...result];
}
}
const sliced = query.split(/ /g);
return [...iterRecur(sliced)];
}
console.log(permutations("this is a test"));
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470762.html
標籤:javascript 细绳 排列
