输入例子:
WHL
输出例子:按字母序输出
HLW HWL LHW LWH WHL WLH
import java.util.Scanner;
import java.util.TreeSet;
public class Main {
public static int count = 0;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String key = scan.nextLine();
TreeSet<String> ts = new TreeSet<String>();
QuanPaiLie(0 , key , ts);
for(String keyStr : ts){
System.out.println(keyStr);
}
}
scan.close();
}
/**
* 求字符串的全排列
* 算法思想:递归
*/
private static void QuanPaiLie(int step, String key , TreeSet<String> ts) {
int length = key.length();
if(step == length - 1){
ts.add(key);
}
for(int i = step ; i < length ; i++){
key = swap(step , i , key); //交换
QuanPaiLie(step + 1 , key ,ts);
key = swap(step , i , key); //恢复
}
}
/**
* 交换字符串中的某两位,返回新的字符串
* */
private static String swap(int a , int b , String str){
//如果要交换的两个下标相等直接返回字符串
if(a == b) return str;
String result = "";
int length = str.length();
char[] strCh = str.toCharArray();
char tempCh = strCh[a];
strCh[a] = strCh[b];
strCh[b] = tempCh;
for(int i = 0 ; i < length ; i++){
result += strCh[i];
}
return result;
}
}