求輸入字符串的全排列

求去重後的全排列的個數,包含重複的個數直接求長度的階乘即可。(自己琢磨,簡單測試通過,有問題請指正)

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        allSortCount(s);
    }
    
    static void allSortCount(String s){
        char[] chars = s.toCharArray();
        List<Character> charList = new ArrayList<>(chars.length);
        for (char c : chars) {
            charList.add(c);
        }
        // 求字符串長度的階乘(此時是全排列的個數,未去重)
        long count = jc(s.length());

        // 求重複元素的個數,只需要有重複的,例 aaabbbccde,最終得到  [3,3,2]
        Collection<Long> collect = charList.stream().collect(Collectors.groupingBy(Character::charValue, Collectors.counting())).values();
        collect.removeIf(e -> e < 1);
        // 重複元素個數的階乘的乘積,(3*2*1)*(3*2*1)*(2*1)
        long dumpCount = 1;
        for (Long value : collect) {
            dumpCount = dumpCount * jc(value.intValue());
        }
        System.out.println("去重後的全排列個數:" + count / dumpCount);
    }

    static int jc(int num) {
        if (num <= 1) {
            return 1;
        }
        int result = num * jc(num - 1);
        return result;
    }

未去重的全排列,想去重可以添加到一個set中(網上抄的,只記錄一下)

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        sort(s.toCharArray(), 0, s.length() - 1);
    }

    static void sort(char[] arr, int begin, int end) {
        if (begin == end) {
            System.out.println(Arrays.toString(arr));
            return;
        }
        for (int i = begin; i <= end; i++) {
            swap1(arr, begin, i);
            sort(arr, begin + 1, end);
            swap1(arr, begin, i);
        }
    }

    static void swap1(char[] arr, int a, int b) {
        char temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章