解密

来源:互联网 发布:详解进化论知乎 编辑:程序博客网 时间:2024/04/29 23:46

>
输入描述:
每组数据输入只有一行,是一个由不同的大写字母组成的字符串,
已知字符串的长度在1到9之间,我们假设对于大写字母有’A’ < ‘B’ < … < ‘Y’ < ‘Z’。
输出描述:
输出这个字符串的所有排列方式,每行一个排列,要求字母序比较小的排列在前面。
输入例子:
WHL
输出例子:
HLW
HWL
LHW
LWH
WHL
WLH

public class 解密 {    public static void main(String[] args) {        Scanner sc=new Scanner(System.in);        String str=sc.nextLine();        sc.close();        char c[]=str.toCharArray();        Set<String> set = new TreeSet<>();//用TreeSet进行排序,使字母比较小的排列在前面        permutaion(set,c,0);        for(String s : set){            System.out.println(s);        }    }     private static void permutaion(Set<String> set, char[] c, int s) {        if(s == c.length){            set.add(String.valueOf(c));         }else{            for(int i = s; i < c.length; i++){//不断将后面所有字符换到这个位上                swap(c,s,i);//换字符                permutaion(set, c, s+1);//深度搜索,用到是换了字符后的状态                swap(c,s,i);//恢复            }        }    }     private static void swap(char[] c, int s, int i) {//交换字符串数组中的两个字符        char t = c[i];        c[i] = c[s];        c[s] = t;    }}