在此示例中,我們將學(xué)習(xí)計算Java中字符串的所有排列組合。
要理解此示例,您應(yīng)該了解以下Java編程主題:
字符串的排列是指可以通過互換字符串字符的位置來形成的所有可能的新字符串。例如,字符串 ABC 具有的排列組合 [ABC,ACB,BAC,BCA,CAB,CBA]。
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
class Main {
public static Set<String> getPermutation(String str) {
//創(chuàng)建 set 集合以避免重復(fù)排列
Set<String> permutations = new HashSet<String>();
//檢查字符串是否為空
if (str == null) {
return null;
} else if (str.length() == 0) {
//遞歸的終止條件
permutations.add("");
return permutations;
}
//得到第一個字符
char first = str.charAt(0);
//獲取剩余的子字符串
String sub = str.substring(1);
//遞歸調(diào)用getPersertion()
Set<String> words = getPermutation(sub);
//遍歷 words
for (String strNew : words) {
for (int i = 0;i<=strNew.length();i++){
//將排列插入到set集合中
permutations.add(strNew.substring(0, i) + first + strNew.substring(i));
}
}
return permutations;
}
public static void main(String[] args) {
//創(chuàng)建scanner類的對象
Scanner input = new Scanner(System.in);
// 接受用戶的輸入
System.out.print("輸入字符串: ");
String data = input.nextLine();
System.out.println(data + " 的排列組合有: \n" + getPermutation(data));
}
}輸出結(jié)果
輸入字符串: ABC ABC 的排列組合有: [ACB, BCA, ABC, CBA, BAC, CAB]
在Java中,我們使用了遞歸來計算字符串的所有排列組合。在這里,我們將排列存儲在set集合中。因此,不會有重復(fù)的排列組合。