java - 如何在Java中打印出字符串的所有排列

标签 java

给定一个字符串,我需要打印出该字符串的所有排列。我该怎么做呢?我已经尝试过了

for(int i = 0; i<word.length();i++)
    {
        for(int j='a';j<='z';j++){
            word = word.charAt(i)+""+(char)j;
            System.out.println(word);   
        }
    }

有什么好的方法吗?

最佳答案

我不能 100% 确定我理解您想要做什么。我将按照您对问题的原始措辞以及您对@ErstwhileIII的答案的评论进行讨论,这让我认为您正在寻找的并不是真正的“排列”(即单词中字母的重新排列),而是可能的单字母修改(也不知道用什么词更好),如下所示:

取一个像“hello”这样的单词,并打印一个列表,其中包含通过添加一个“拼写错误”可以获得的所有“版本”:

你好 -> aello、bello、大提琴、...、zello、hallo、hbllo、hcllo、...、hzllo、healo、heblo、...

如果这确实是您正在寻找的内容,以下代码将非常有效地为您完成此操作:

public void process(String word) {
    // Convert word to array of letters
    char[] letters = word.toCharArray();
    // Run through all positions in the word
    for (int pos=0; pos<letters.length; pos++) {
        // Run through all letters for the current position
        for (char letter='a'; letter<='z'; letter++) {
            // Replace the letter
            letters[pos] = letter;
            // Re-create a string and print it out
            System.out.println(new String(letters));
        }
        // Set the current letter back to what it was
        letters[pos] = word.charAt(pos);
    }
}

关于java - 如何在Java中打印出字符串的所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22444410/

相关文章:

java - 如何在访问公共(public)静态最终变量时设置断点?

java - Hibernate CriteriaBuilder 将多行连接成一行

java - 使用java对空结果集进行sql错误非法操作

java - 如何在 Java 中解析日期?日期格式有些困惑

java - Eclipse : "The project cannot be built until build path errors are resolved" 错误

java - Spoj NZEC 错误

java - 使用 Java 将文件从一个目录 move 到另一个目录

java - 使用java从一个oracle数据库中选择并批量插入到另一个oracle数据库中

java - 如何在 Eclipse 中以编程方式打开编辑器上的文件?

java - 将 JPanel 转换为 png 或其他图像文件