3 回答
TA贡献1843条经验 获得超7个赞
像二叉树一样遍历字符串
const permute = (str, prefix='') => {
const idx = prefix.length
if (idx===str.length)
return [prefix]
const lower = str[idx].toLowerCase()
const upper = str[idx].toUpperCase()
return [...permute(str, prefix + lower), ...permute(str, prefix + upper)]
}
console.log(permute('abc'))
TA贡献1829条经验 获得超7个赞
这是一个带有 flatMap 的:
function f(str){
return str ? f(str.slice(1)).flatMap(sfx =>
[str[0].toLowerCase() + sfx, str[0].toUpperCase() + sfx]) : [""]
}
console.log(JSON.stringify(f("abc")))
TA贡献2037条经验 获得超6个赞
您可以采用递归函数,该函数采用最后访问的索引的收集字母,并检查收集的字母字符串是否与给定字符串的长度相同。然后将字符串推送到结果集。
关键是递归调用一个小写字母和一个大写字母。
function capitalPermutations(word) {
function iter(temp = '') {
if (temp.length === word.length) {
result.push(temp);
return;
}
iter(temp + word[temp.length].toLowerCase());
iter(temp + word[temp.length].toUpperCase());
}
var result = [];
iter();
return result;
}
console.log(capitalPermutations('abc'));
与迭代方法相同
function capitalPermutations(word) {
var result = [''],
temp,
i, j, upper, lower;
for (i = 0; i < word.length; i++) {
temp = result;
result = [];
lower = word[i].toLowerCase();
upper = word[i].toUpperCase();
for (j = 0; j < temp.length; j++) {
result.push(temp[j] + lower, temp[j] + upper);
}
}
return result;
}
console.log(capitalPermutations('abc'));
添加回答
举报