查找java中的字符串的所有排列
时间:2020-02-23 14:34:09 来源:igfitidea点击:
在本教程中,我们将看到如何在Java中找到字符串的所有排列。
我们将使用一个非常简单的方法来完成它。
Take out first character of String and insert into different places of permutations of remaining String recursively.
让我们说你是ABC的字符串。
因此,我们从ABC第一个角色= A和RemainingString = BC,我们在这里申请递归,我们会发现BC的排列。
从BC取出B.第一个字符= B和RemainingString = C当我们在此处应用递归时,我们会发现C的排列。
当我们取出C时,我们的字符串大小将变为0,这是我们的基本情况。
第一个字符= c和remainingstring =""""我们将c插入剩余字符串排列的差异索引(""),因此我们将C的排列作为C.我们将B插入到剩余的汇流(c)的不同索引中,所以我们得到BC和CB。
C:BC,CB现在我们在BC和CB中插入到不同的索引。
BC:ABC,BAC,BCA CB:ACB,CAB,CBA,所以我们如何获得ABC的所有排列。
它可能看起来很棘手,但一旦你练习解决方案,你就可以更好地理解它。
java程序查找java中的所有字符串排列:
package org.igi.theitroad;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class PermutationOfStringJava {
public static void main(String[] args) {
Set set=permutationOfString("ABC");
System.out.println("Permutations of String ABC are:");
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
String string = (String) iterator.next();
System.out.println(string);
}
}
public static Set permutationOfString(String str)
{
Set permutationSet=new HashSet();
if(str.length()==0)
{
permutationSet.add("");
return permutationSet;
}
//take out first character of String
char c=str.charAt(0);
//Remaining String
String rem=str.substring(1);
Set permutatedSetForRemainingString=permutationOfString(rem);
for (String permutedString: permutatedSetForRemainingString) {
for (int j = 0; j <= permutedString.length(); j++) {
String permutation=insertFirstCharAtDiffPlaces(permutedString,c,j);
permutationSet.add(permutation);
}
}
return permutationSet;
}
public static String insertFirstCharAtDiffPlaces(String perm,char firstChar,int index)
{
//Inserting firstCharacter of orig String at difference places based on index
return perm.substring(0,index)+firstChar+perm.substring(index);
}
}
运行上述程序时,我们将完成以下操作:
Permutations of String ABC are: ACB ABC BCA CBA CAB BAC

