javascript - 字符串排列时的递归问题
问题描述
我正在尝试生成字符串的所有大写排列。
例如:
capitalPermutations(word) - 给定一串字母,返回该单词的所有可能的小写和大写字母组合。
示例:'abc'
输出:['abc''Abc''aBc''ABc''abC''AbC''aBC''ABC']
以迭代和递归的方式实现这一点。
这是我的尝试:
function capitalPermutations(word) {
const res = new Set();
// Push the actual word first.
res.add(word);
helper(word, res, '');
return res;
function helper(word, res, str='') {
if(str.length === word.length) return;
const len = word.length;
res.add(word);
// Capitalization
for(let i=0; i< word.length; i++) {
const substr = word.substring(0, i+1); // a, ab, abc
str += substr; // str === "ABC" | len = 3
const upper = str.toUpperCase(); // A, AB, ABC
const remaining = `${upper}${word.substring(i, len)}`; // Abc , ABc,
helper(remaining, res, str);
}
}
}
var testWord1 = "abc"
console.log(capitalPermutations(testWord1))
问题: 它将进入无限递归。即使我有一个破碎的条件。如果有人能纠正我出错的地方,我将不胜感激。
解决方案
这是一个带有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")))
推荐阅读
- spring-boot - Failed to start bean 'inputBindingLifecycle' - A consumer group is required for a partitioned subscription
- amazon-web-services - Adding null partition value to the glue table
- python - Multiplication on the command line using argparse
- python - Python 导入 ModuleNotFoundError
- numpy - How Can I Find Peak Values of Defined Areas from Spectrogram Data using numpy?
- arrays - how can I create json data structure in mongodb like this?
- c# - 如何在应用程序中的客户端之间创建隔离
- vue.js - Changes in aria-live area not read properly on client-side search results in Vue 2
- automated-tests - When we run the testsuite from CI/CD, where would the allure report be created in git repository?
- javascript - Redux Persist looses data when I redirect to a different page