字符组合生成器:如何实现按最小/最大长度生成指定数量字符串
字符组合生成功能的修复方案
需求与问题
我需要实现一个字符组合生成功能,需求如下:
- 用户可定义字符串的最小长度、最大长度、可用字符集以及需要生成的字符串数量
目前代码仅能生成等于最大长度的字符组合,比如设置maxLength=4时,只生成4位长度的字符串,无法覆盖minLength到maxLength之间的所有长度(例如minLength=2、maxLength=5时,需要生成2-5位的所有组合)。
核心代码
private void iterate(char[] chars, int maxLength, int minLength, int howMany, char[] build, int pos) { while (check < howMany) { if (pos == maxLength || ????) { // 这里需要修改 Word word = new Word(null, new String(build)); SetOfWords.add(word); save(word); check++; return; } for (int i = 0; i < chars.length; i++) { build[pos] = chars[i]; iterate(chars, maxLength, minLength, howMany, build, pos + 1); } } }
当前输出示例
[ { "id": 1, "word": "aaaa" }, { "id": 4, "word": "aaad" }, { "id": 2, "word": "aaab" }, { "id": 3, "word": "aaac" }, { "id": 5, "word": "aaba" } ]
修改方案
核心是调整终止条件与结果保存逻辑:当当前构建的字符串长度(pos)达到最小长度时,就将其加入结果集,同时继续递归生成更长的字符串直到最大长度。
1. 调整判断逻辑
将原有的单if拆分为两个逻辑:
- 先判断当前长度是否达到最小要求,满足则保存字符串
- 再判断是否达到最大长度,满足则终止递归
2. 修改后的完整核心代码
private void iterate(char[] chars, int maxLength, int minLength, int howMany, char[] build, int pos) { while (check < howMany) { // 当当前长度达到最小长度时,保存当前已构建的字符串 if (pos >= minLength) { // 注意:这里要截取build数组的前pos位,避免包含未初始化的字符 Word word = new Word(null, new String(build, 0, pos)); SetOfWords.add(word); save(word); check++; // 生成数量达标后直接终止 if (check >= howMany) { return; } } // 达到最大长度时停止递归,不再生成更长的字符串 if (pos == maxLength) { return; } for (int i = 0; i < chars.length; i++) { build[pos] = chars[i]; iterate(chars, maxLength, minLength, howMany, build, pos + 1); } } }
3. 逻辑说明
- 每次递归到
pos >= minLength时,都会保存当前长度的字符串,同时继续递归生成更长的组合 - 使用
new String(build, 0, pos)确保只截取已构建的有效字符,避免出现多余的空字符或旧值 - 每次保存后检查是否达到指定生成数量,达标后立即终止所有递归流程
这样修改后,就能覆盖从minLength到maxLength之间的所有长度,直到生成满足数量要求的字符组合。
内容的提问来源于stack exchange,提问作者Fellou98
相关产品推荐
相关产品推荐

