字符串的排序 java

版权声明:博客内容为本人自己所写,请勿转载。 https://blog.csdn.net/weixin_42805929/article/details/83306850

字符串的排序 java

题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

代码1

import java.util.*;

public class Solution {
    public static ArrayList<String> Permutation(String str) {
		ArrayList<String> al = new ArrayList<>();
		if (str != null && str.length() > 0) {
			PermutationHelper(str.toCharArray(), 0, al);
			Collections.sort(al);
		}
		return (ArrayList<String>) al;
	}

	public static void PermutationHelper(char[] c, int start, ArrayList<String> al) {
		if (start == c.length - 1) {
			String st = String.valueOf(c);
			if (!al.contains(st)) {
				al.add(st);
			}
		} else {
			for (int j = start; j < c.length; j++) {
				swap(c, start, j);
				PermutationHelper(c, start + 1, al);
				swap(c, start, j);//复位
			}
		}
	}

	public static void swap(char[] c, int i, int j) {
		if(i != j) {
			char temp = c[i];
			c[i] = c[j];
			c[j] = temp;
		}
	}
}

代码2:

猜你喜欢

转载自blog.csdn.net/weixin_42805929/article/details/83306850