[Offer] [38] [in] string arrayed

Title Description

  A string input, prints out all permutations of the characters in the string. For example, input string abc, abc print all strings that can be ordered out by the character a, b, c, acb, bac, bca, cab and cba.
  

Cattle brush off questions address network

Ideas analysis

  The character string as two portions, the first portion of the first character position, the second portion of the remaining characters, then, this operation requires a string can be divided into two steps:
  1. The demand may occur in the first portion the first character position, that is the first character and all characters following the exchange
  2. demand behind the character of the arrangement, which went back to the original question. You can use recursion.

Test Case

  1. Functional test: the input string with one or more characters.
  2. Special input test: the contents of the input string is empty or nullptr pointer.

Java code

public class Offer38 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();
        
    }

    public ArrayList<String> Permutation(String str) {
        return Solution1(str);
    }

    private static ArrayList<String> Solution1(String str) {
        ArrayList<String> list = new ArrayList<String>();
        if(str==null || str.length()==0){
            return list;
        }
        permutationCore(str.toCharArray(),0,list);
        Collections.sort(list);
        return list;
    }
    
     private static void permutationCore(char[] array,int index,ArrayList<String> list){
            if(index == array.length-1){
                if(!list.contains(String.valueOf(array))){
                    list.add(String.valueOf(array));
                }
            }else{
                for(int i=index;i<array.length;i++){
                    char tmp = array[index];
                    array[index] = array[i];
                    array[i] = tmp;
                    permutationCore(array,index+1,list);
                    array[i]=array[index];
                    array[index] = tmp;   
                }
            }
        }

    private static void test1() {

    }

    private static void test2() {

    }
    private static void test3() {

    }

}

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/offer38-zi-fu-chuan-de-pai-lie.html
38