題目描述
輸入一個字串,按字典序列印出該字串中字符的所有排列。例如輸入字串abc,則按字典序列印出由字符a,b,c所能排列出來的所有字串abc,acb,bac,bca,cab和cba。
我的代碼:
public class Permutation {
private static ArrayList<String> result = new ArrayList<String>();
public static void main(String[] args) {
String str = "abc";
permutation(str);
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i));
}
}
public static ArrayList<String> permutation(String str) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
result.add(String.valueOf(chars));
swap(chars);
return result;
}
public static void swap(char[] chars) {
if (chars.length == 1) {
return;
}
swap(Arrays.copyOfRange(chars, 1, chars.length));
for (int i = 1; i < chars.length; i++) {
char[] copy = Arrays.copyOf(chars, chars.length);
char temp = chars[i];
for (int j = i-1; j >= 0 ; j--) {
copy[j+1] = copy[j];
}
copy[0] = temp;
result.add(String.valueOf(copy));
swap(Arrays.copyOfRange(copy, 1, copy.length));
}
}
}運行結果:

有沒有高手回答下,怎么改能輸出缺失的字符,我不知道怎么把每次交換的結果和原來的字串拼接起來,謝謝
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/188008.html
標籤:Java SE
