如何在Java中查找字符串的所有排列
时间:2020-02-23 14:37:23 来源:igfitidea点击:
在本教程中,我们将学习如何在Java程序中查找字符串的排列。
这是一个棘手的问题,主要是在Java访谈中问到的。
Java中字符串置换的算法
我们将首先从String中获取第一个字符,并用剩余的字符进行置换。
如果String =" ABC"
第一个字符= A,剩余的字符排列为BC和CB。
现在我们可以在排列的可用位置插入第一个字符。
卑诗省-> ABC,BAC,BCA
CB-> ACB,CAB,CBA
我们可以编写一个递归函数以返回排列,然后编写另一个函数以插入第一个字符以获取排列的完整列表。
Java程序打印字符串的排列
package com.theitroad.java.string;
import java.util.HashSet;
import java.util.Set;
/**
* Java Program to find all permutations of a String
* @author hyman
*
*/
public class StringFindAllPermutations {
public static Set<String> permutationFinder(String str) {
Set<String> perm = new HashSet<String>();
//Handling error scenarios
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<String> 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));
}
}
我用Set来存储字符串排列。
这样可以自动删除重复项。
输出
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]

