java - 查找单词中不重复字母的所有排列
问题描述
给定 3 个唯一字母:您能否使用递归函数打印六种可能的非重复字母组合。'cat' 应该输出:cat、act、atc、tac、tca 和 cta。这是我的程序,我无法找到递归算法。这是我的尝试:
static void findWords(StringBuilder string, int start, int stride) {
//1. iterate through all possible combinations of the chars recursively
System.out.println(string);
if (stride < string.length() && start < string.length())
{
char temp = string.charAt(stride);
string.setCharAt(stride, string.charAt(start));
string.setCharAt(start, temp);
findWords(string, start, stride + 1);
findWords(string, start + 1, stride + 1 );
}
}
public static void main(String[] args)
{
StringBuilder word = new StringBuilder("cat");
findWords(word,0,1);
}
解决方案
我使用的算法非常简单。使每个字符成为字符串的第一个字符,并找到与其他两个字符的组合。所以对于字符 c、a、t 的组合将是
c at
c ta
a ct
a tc
t ca
t ac
代码:
static void findWords(String str, int pos) {
if(str == null || pos < -1) {
return;
}
int len = str.length();
if(pos + 1 < len) {
findWords(str, pos + 1);
}
//find char swap positions
int pos1 = (pos + 1) % len;
int pos2 = (pos - 1 + len) % len;
char[] chars = str.toCharArray();
String str1 = new String(new char[] {chars[pos], chars[pos1], chars[pos2]});
String str2 = new String(new char[] {chars[pos], chars[pos2], chars[pos1]});
System.out.println(str1);
System.out.println(str2);
}
public static void main(String[] args) {
String word = new String("abc");
findWords(word, 0);
}
推荐阅读
- google-apps-script - 在 Apps 脚本中使用 getValues() 时,如何确保 Google 工作表更新 importRange()
- javascript - 控制台中的错误显示 main.js 中出现错误的不是特定文件的错误
- parsing - ANTLR 语法未按预期工作。我究竟做错了什么?
- rest - Delphi 如何创建 JSON Web Keys (jwk)
- reactjs - 如果我在 Input 标签中搜索任何内容,如果我有该数据,它必须显示,否则它必须显示没有结果
- shopify - 为 Shopify 创建结帐时变体 ID 无效
- azure - Swagger 连接到 Azure ..现在呢?
- android - 如何在android中更改按钮的背景并在几秒钟后保留它
- javascript - d3 刻度,每隔 N 天均匀放置刻度
- amazon-web-services - Elastic Beanstalk:504 网关超时 - 访问端点时下载图像