// 输出给定的字符串的所有的组合
//输入:“AAB”
//输出:8
//解释:可能的序列为 “A”, “B”, “AA”, “AB”, “BA”, “AAB”, “ABA”, “BAA”。
//MAX_Len(Str) == 7
public static void main(String[] args) {
System.out.println(subStrCount("aab")); // 8
System.out.println(subStrCount("abc")); // 15
}
static int subStrCount(String str) {
Map<Character, Integer> map = new HashMap<>();
for (int i =0 ; i< str.length(); i++) {
char ch = str.charAt(i);
if (map.containsKey(ch)) map.put(ch, map.get(ch) + 1);
else map.put(ch ,1);
}
int[] temp = new int[9];
for (int i = 0; i< 9 ;i++) temp[i] = 0;
Set<Character> set = map.keySet();
for (Character ch :set) {
for (int i = 7; i> 0; i--) temp[i+1] += cnm(i + map.get(ch), i) * temp[i];
for (int i = 1; i<= map.get(ch); i++) temp[i] = temp[i] + 1;
}
int result = 0;
for (int i = 1; i< 8; i++) result += temp[i];
return result;
}
/**
* 计算 组合数 公式
* @param n 元素总个数
* @param m 参与选择的元素个数
* @return
*/
static int cnm(int n, int m) {
int result = 1;
for (int i= 1; i <= m ; i++) {
result = result * (n - i + 1);
}
for (int i= 1; i <= m ; i++) {
result = result / i;
}
return result;
}