如何在 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 Repository 下載範例程式碼。

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