Jerry的挑戰
author: Qiangwei Luo (OVEA)
問題概述:
有一天Jerry給Tom出了一道題來考驗他。
Jerry給了Tom一個長度爲2*
n的只包含小寫字母的字符串,讓Tom將這個字符串任意挑選字符,將其分成兩個等長的字符串a和b(對於一個si不能同時被選到a和b中),然後a要和reverse(b)相同(a和反轉後的b相同),問這樣的方案數有多少?Tom有些爲難,所以請你來幫幫他吧。
輸入一個正整數n,和一個長度爲2*n的字符串。
輸出方案數。
示例1
輸入:
2
“abba”
輸出:
4
題解:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class JerryTest {
public long solution(int n, String s) {
boolean isSame = false;
for (int i = 0; i < s.length(); i++) {
isSame = true;
if (s.charAt(0) != s.charAt(i)) {
isSame = false;
break;
}
}
// 如果都是同樣的字母這種情況
if (isSame) {
return C(n, n * 2);
} else {
// 普通情況
// 檢查字符是否無法構成
// 用來檢查字母
int[] store = new int[26];
for (int i = 0; i < s.length(); i++) {
store[s.charAt(i) - 'a']++;
}
for (int i = 0; i < store.length; i++) {
if (store[i] % 2 != 0) return 0;
}
// 可匹配的情況
return dfs(s, n, "", 0, "");
}
}
/**
* 需要的信息 原始字符串,當前加入的位置,當前使用過的字符標記等
* @param s 原始字符串
* @param n 一半單詞的數量
* @param left 左半邊的詞
* @param index 當前指向原始字符串的位置
* @param right 右半邊的值
* @return 匹配數量
*/
private long dfs(String s, int n, String left, int index, String right) {
int sum = 0;
// 遞歸終止條件,left已經到達N了
if (left.length() == n) {
// 補完right的部分
for (int i = index; i < s.length(); i++) {
right += s.charAt(i);
}
// System.out.println(t + " " + left);
if (left.equals(new StringBuilder(right).reverse().toString())) {
return 1;
}
return 0;
}
for (int i = index; i < 2 * n; i++) {
// right的部分
String tmpStr = right;
for (int j = index; j < i; j++) {
tmpStr += s.charAt(j);
}
// 統計通過的示例
sum += dfs(s, n, left + s.charAt(i), i + 1, tmpStr);
}
// 返回結果到上一層,直到第一層返回給solution方法
return sum;
}
/**
*
* @param up 上標
* @param down 下標
* @return 排列組合數量
*/
private long C(int up, int down) {
int a = 1;
for (int i = down; i > up; i--) {
a *= i;
}
int b = 1;
for (int i = up; i > 0; i--) {
b *= i;
}
return a / b;
}
/**
* 測試算法結果
*/
@Test
public void test() {
// System.out.println(solution(1, "ab"));
// System.out.println(solution(2, "abcd"));
System.out.println(solution(2, "abba"));//4
Assertions.assertEquals(solution(2, "abba"), 4);
System.out.println(solution(4, "cabaacba"));//4
Assertions.assertEquals(solution(4, "cabaacba"), 4);
System.out.println(solution(15, "dirjbtsgiilnbbjjbbnliigstbjrid")); //73728
Assertions.assertEquals(solution(15, "dirjbtsgiilnbbjjbbnliigstbjrid"), 73728);
System.out.println(solution(11, "mippiisssisssiipsspiim")); // 504
Assertions.assertEquals(solution(11, "mippiisssisssiipsspiim"), 504);
// System.out.println(solution(2, "aaaa"));
// System.out.println(CombinationNumberCalculation.nchoosek(4, 2));
// System.out.println(JerrySolution.solution(2, "aaaa"));
}
}