一、概念
現(xiàn)有一個字符串,要打印出該字符串中字符的全排列。
以字符串a(chǎn)bc為例,輸出的結(jié)果為:abc、acb、bac、bca、cab、cba。
以字符串a(chǎn)ab為例,輸出的結(jié)果為:aab、aba、baa。
二、代碼
public class Permutation {
? ? public static void main(String[] args) {
? ? ? ? List<String> list = getPermutation("abca");
// ? ? ? ?輸出結(jié)果
? ? ? ? dump(list);
? ? }
// ? ?輸出結(jié)果
? ? public static void dump(List<String> list) {
? ? ? ? if (null != list) {
? ? ? ? ? ? for (String str : list) {
? ? ? ? ? ? ? ? System.out.println(str);
? ? ? ? ? ? }
? ? ? ? }
? ? }
// ? ?從字符串str獲取全排列結(jié)果
? ? public static List<String> getPermutation(String str) {
? ? ? ? if (null == str) {
? ? ? ? ? ? return null;
? ? ? ? }
? ? ? ? char[] array = str.toCharArray();
? ? ? ? Arrays.sort(array);
? ? ? ? List<String> list = new ArrayList<>();
// ? ? ? ?進行全排列操作
? ? ? ? permutationIteration(array, 0, list);
? ? ? ? Collections.sort(list);
? ? ? ? return list;
? ? }
// ? ?全排列操作
? ? public static List<String> permutationIteration(char[] array, int index, List<String> list) {
? ? ? ? //到達子遞歸操作的最后,將結(jié)果加入列表
? ? ? ? if (index == array.length - 1) {
? ? ? ? ? ? list.add(String.valueOf(array));
? ? ? ? ? ? return list;
? ? ? ? }
? ? ? ? for (int i = index; i < array.length; i++) {
? ? ? ? ? ? //當要交換的字符值相同時,則交換是使結(jié)果重復的操作,故不予交換
? ? ? ? ? ? if (i != index && array[i] == array[index]) {
? ? ? ? ? ? ? ? continue;
? ? ? ? ? ? }
? ? ? ? ? ? //交換2個位置的字符
? ? ? ? ? ? swap(index, i, array);
// ? ? ? ? ? ?遞歸調(diào)用獲取結(jié)果
? ? ? ? ? ? permutationIteration(array, index + 1, list);
// ? ? ? ? ? 將交換操作還原回去
? ? ? ? ? ? swap(index, i, array);
? ? ? ? }
? ? ? ? return list;
? ? }
? ? /**
? ? ?* array: ?字符數(shù)組
? ? ?* 交換字符數(shù)組中2個位置的字符
? ? ?*/
? ? public static void swap(int index1, int index2, char[] array) {
? ? ? ? if (index1 != index2) {
? ? ? ? ? ? char tmp = array[index1];
? ? ? ? ? ? array[index1] = array[index2];
? ? ? ? ? ? array[index2] = tmp;
? ? ? ? }
? ? }
}
致力于C、C++、Java、Kotlin、Android、Shell、JavaScript、TypeScript、Python等編程技術的技巧經(jīng)驗分享。文章來源:http://www.zghlxwxcb.cn/news/detail-853036.html
若作品對您有幫助,請關注、分享、點贊、收藏、在看、喜歡。您的支持是我們?yōu)槟峁椭淖畲髣恿Α?span toymoban-style="hidden">文章來源地址http://www.zghlxwxcb.cn/news/detail-853036.html
到了這里,關于獲取字符串的全排列(去除字符串中2個字符相同時造成的重復)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!