字符串的排列
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
代码实现
package 剑指offer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
/**
* @author WangXiaoeZhe
* @Date: Created in 2019/11/22 18:02
* @description:
*/
public class Main16 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
ArrayList<String> permutation = Permutation(s);
for (String s1 : permutation) {
System.out.println(s1);
}
}
public static ArrayList<String> Permutation(String str) {
ArrayList<String> list = new ArrayList<String>();
char[] ch = str.toCharArray();
Permu(ch, 0, list);
Collections.sort(list);
return list;
}
public static void Permu(char[] str, int i, ArrayList<String> list) {
if (str == null) {
return;
}
if (i == str.length - 1) {
if(list.contains(String.valueOf(str))){
return;
}
list.add(String.valueOf(str));
} else {
for (int j = i; j < str.length; j++) {
swap(str,i,j);
Permu(str, i + 1, list);
swap(str,i,j);
}
}
}
public static void swap(char[] str, int i, int j) {
char tmp = str[i];
str[i] = str[j];
str[j] = tmp;
}
}