标签:
1 import java.util.ArrayList; 2 public class Solution { 3 public ArrayList<String> Permutation(String str) { 4 return findPermutationStr(str); 5 6 } 7 private static ArrayList<String> findPermutationStr(Stringstr) { 8 ArrayList<String> strList= findPermutations(str); 9 ArrayList<String> strList2 = new ArrayList<String>(); 10 for (int i = 0; i < strList.size(); i++) { 11 if (!strList2.contains(strList.get(i))) { 12 strList2.add(strList.get(i)); 13 } 14 15 } 16 String tmpString = null; 17 // [aabc, abac, abca, aacb, acab, acba, baac, baca, bcaa, caab, caba, 18 // cbaa] 19 for (int i = 0; i < strList2.size(); i++) { 20 for (int j = 0; j < strList2.size() - 1 - i; j++) { 21 if (compareStr(strList2.get(j), strList2.get(j+1)) >0) { 22 tmpString = strList2.get(j); 23 strList2.set(j, strList2.get(j + 1)); 24 strList2.set(j + 1, tmpString); 25 } 26 } 27 } 28 return strList2; 29 } 30 private static ArrayList<String> findPermutations(String str) { 31 ArrayList<String> strList = new ArrayList<String>(); 32 if (str.length() == 0) { 33 return strList; 34 } 35 if (str.length() == 1) { 36 strList.add(str); 37 return strList; 38 } 39 if (str.length() == 2) { 40 char[] chArry = str.toCharArray(); 41 strList.add(str); 42 if (chArry[0] != chArry[1]) { 43 String s = new String(new char[] { chArry[1], chArry[0] }); 44 strList.add(s); 45 } 46 47 return strList; 48 } 49 50 ArrayList<String> subStrPermutation敏感词indPermutations(str.substring(1)); 51 char firstChar = str.charAt(0); 52 for (String s : subStrPermutations) { 53 String tmpStr = firstChar + s; 54 strList.add(tmpStr); 55 char[] charArry = tmpStr.toCharArray(); 56 for (int i = 0; i < tmpStr.length() - 1; i++) { 57 char t = charArry[i]; 58 charArry[i] = charArry[i + 1]; 59 charArry[i + 1] = t; 60 strList.add(new String(charArry)); 61 } 62 } 63 return strList; 64 } 65 66 static int compareStr(String str1, String str2) { 67 if (str1.length() != str2.length()) { 68 return str1.length() > str2.length() ? 1 : -1; 69 } 70 for (int i = 0; i < str1.length(); i++) { 71 if (str1.charAt(i) == str2.charAt(i)) { 72 continue; 73 } 74 return str1.charAt(i) > str2.charAt(i)?1:-1; 75 76 } 77 return 0; 78 } 79 }
标签:
原文地址:http://www.cnblogs.com/huntertoung/p/4803180.html