如何用 Java 查找字符串的所有排列方式

在本教程中,我们将学习如何在Java程序中找到一个字符串的转换,这是一个棘手的问题,主要是在Java采访中提问。

Java 中的 String Permutation 算法

如果 String = "ABC" 第一個 char = A 和剩餘的 char 轉換是 BC 和 CB. 現在我們可以插入第一個 char 在可用的位置中的轉換. BC -> ABC, BAC, BCA CB -> ACB, CAB, CBA 我們可以寫回歸函數返回轉換,然後另一個函數插入第一個字符,以獲得完整的轉換列表。

Java 程序来打印字符串的可变性

 1package com.journaldev.java.string;
 2
 3import java.util.HashSet;
 4import java.util.Set;
 5
 6/**
 7 * Java Program to find all permutations of a String
 8 * @author Pankaj
 9 *
10 */
11public class StringFindAllPermutations {
12    public static Set<String> permutationFinder(String str) {
13        Set<String> perm = new HashSet<String>();
14        //Handling error scenarios
15        if (str == null) {
16            return null;
17        } else if (str.length() == 0) {
18            perm.add("");
19            return perm;
20        }
21        char initial = str.charAt(0); // first character
22        String rem = str.substring(1); // Full string without first character
23        Set<String> words = permutationFinder(rem);
24        for (String strNew : words) {
25            for (int i = 0;i<=strNew.length();i++){
26                perm.add(charInsert(strNew, initial, i));
27            }
28        }
29        return perm;
30    }
31
32    public static String charInsert(String str, char c, int j) {
33        String begin = str.substring(0, j);
34        String end = str.substring(j);
35        return begin + c + end;
36    }
37
38    public static void main(String[] args) {
39        String s = "AAC";
40        String s1 = "ABC";
41        String s2 = "ABCD";
42        System.out.println("\nPermutations for " + s + " are: \n" + permutationFinder(s));
43        System.out.println("\nPermutations for " + s1 + " are: \n" + permutationFinder(s1));
44        System.out.println("\nPermutations for " + s2 + " are: \n" + permutationFinder(s2));
45    }
46}

我用 Set存储字符串转换,以便自动删除重复。

出口

1Permutations for AAC are: 
2[AAC, ACA, CAA]
3
4Permutations for ABC are: 
5[ACB, ABC, BCA, CBA, CAB, BAC]
6
7Permutations for ABCD are: 
8[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 存储库下载示例程序代码。

Published At
Categories with 技术
Tagged with
comments powered by Disqus