题解 | #字符串的排列#
字符串的排列
http://www.nowcoder.com/practice/4f31423f126749ab9196c97c5117bcb9
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
ArrayList<String> ans=new ArrayList<>();
String res=sc.nextLine();
char[] arr=res.toCharArray();
reverse(arr,0,arr.length-1,ans);
HashSet<String> tmp=new HashSet<>(ans);
ans.clear();
for(String a:tmp){
ans.add(a);
}
Collections.sort(ans);
System.out.print(ans);
}
public static void reverse(char[] arr,int index,int len,ArrayList<String> ans){
if(len==index){
ans.add(change(arr));
}
for(int i=index;i<=len;i++){
char tmp=arr[i];
arr[i]=arr[index];
arr[index]=tmp;
reverse(arr,index+1,len,ans);
tmp=arr[i];
arr[i]=arr[index];
arr[index]=tmp;
}
}
private static String change(char[] arr){
StringBuilder ans=new StringBuilder();
for(char tmp:arr){
ans.append(tmp);
}
return ans.toString();
}
}