如何在Java中找到字符串的所有排列

在本教程中,我们将学习如何在Java程序中找到字符串的排列。这是一个棘手的问题,通常在Java面试中被问到。

Java中字符串排列的算法

我们首先从字符串中取出第一个字符,然后与剩余字符进行排列组合。如果字符串为“ABC”,第一个字符为A,剩余字符的排列组合为BC和CB。现在我们可以将第一个字符插入排列组合中的可用位置。BC -> ABC,BAC,BCA CB -> ACB,CAB,CBA 我们可以编写一个递归函数来返回排列组合,然后另一个函数来插入第一个字符,以获取完整的排列列表。

Java程序打印字符串的排列

package com.journaldev.java.string;

import java.util.HashSet;
import java.util.Set;

/**
 * Java Program to find all permutations of a String
 * @author Pankaj
 *
 */
public class StringFindAllPermutations {
    public static Set permutationFinder(String str) {
        Set perm = new HashSet();
        //处理错误情况
        if (str == null) {
            return null;
        } else if (str.length() == 0) {
            perm.add("");
            return perm;
        }
        char initial = str.charAt(0); // first character
        String rem = str.substring(1); // Full string without first character
        Set words = permutationFinder(rem);
        for (String strNew : words) {
            for (int i = 0;i<=strNew.length();i++){
                perm.add(charInsert(strNew, initial, i));
            }
        }
        return perm;
    }

    public static String charInsert(String str, char c, int j) {
        String begin = str.substring(0, j);
        String end = str.substring(j);
        return begin + c + end;
    }

    public static void main(String[] args) {
        String s = "AAC";
        String s1 = "ABC";
        String s2 = "ABCD";
        System.out.println("\nPermutations for " + s + " are: \n" + permutationFinder(s));
        System.out.println("\nPermutations for " + s1 + " are: \n" + permutationFinder(s1));
        System.out.println("\nPermutations for " + s2 + " are: \n" + permutationFinder(s2));
    }
}

I have used Set to store the string permutations. So that duplicates are removed automatically.

输出

Permutations for AAC are: 
[AAC, ACA, CAA]

Permutations for ABC are: 
[ACB, ABC, BCA, CBA, CAB, BAC]

Permutations for ABCD are: 
[DABC, CADB, BCAD, DBAC, BACD, ABCD, ABDC, DCBA, ADBC, ADCB, CBDA, CBAD, DACB, ACBD, CDBA, CDAB, DCAB, ACDB, DBCA, BDAC, CABD, BADC, BCDA, BDCA]

这就是在Java中找到字符串所有排列的全部内容。

您可以从我们的GitHub存储库下载示例程序代码。

Source:
https://www.digitalocean.com/community/tutorials/permutation-of-string-in-java