/** * Created by stms130834 on 2014/4/28. */ public class TheLuckyString { public static void main(String[] args) { TheLuckyString t = new TheLuckyString(); //nhhhhhalrn //zzddvveett 39480 System.out.println(t.count("aabbbaa")); } public int count(String s) { int[] letters = new int[26]; for (int i = 0; i < s.length(); i++) { letters[s.charAt(i) - 'a']++; } int total = 0; for(int i=0;i<letters.length;i++){ if(letters[i] > 0 ) { String prefix = ""+(char)('a'+i); int[] newLetters = new int[26]; System.arraycopy(letters,0, newLetters, 0, 26); newLetters[i]--; int solutionsCount = findSolutionsCount(prefix, newLetters, s); total+=solutionsCount; } } return total; } private int findSolutionsCount(String prefix, int[] letters, String s) { int total = 0; if(s.length() == prefix.length()) { System.out.println(prefix); return 1; } for(int i=0;i<letters.length;i++){ char c = (char)('a'+i); if(letters[i] > 0 && c != prefix.charAt(prefix.length()-1)) { int[] newLetters = new int[26]; System.arraycopy(letters,0, newLetters, 0, 26); newLetters[i]--; prefix+=c; int solutionsCount = findSolutionsCount(prefix, newLetters, s); total+=solutionsCount; } } return total; } }