字符串顺序排列

时间:2024-10-13 21:10:47
public class Permutation{ private static ArrayList<String> list = new ArrayList<>(); public static ArrayList<String> permutation(String str) { if(str == null){ return list; } permutation(str.toCharArray() , 0); return list; } private static void permutation(char[] chars , int ops){ if(ops == chars.length-1){ //这里需要这步操作是因为如果list直接添加(),最后遍历list时打印出来是hash值, //这里涉及到toString方法的重写,可以了解下。 StringBuffer sb = new StringBuffer(); for(char c : chars){ sb.append(c); } if(!list.contains(sb.toString())){ list.add(sb.toString()); } } for(int i = ops ; i<chars.length;i++){ char temp = chars[i]; chars[i] = chars[ops]; chars[ops] = temp; permutation(chars,ops+1); temp = chars[i]; chars[i] = chars[ops]; chars[ops] = temp; } } }