给定一个字符串,我需要打印出该字符串的所有排列。我该怎么做呢?我已经尝试过了
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/