题目详情
点击查看
有一天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
解题思路
在原字符串中抽出n个字符的字符串a,字符顺序保持不变,剩下的字符都给字符串b,比较a和reverse(b)是否相同(a和反转后的b是否相同)
参考代码
package solution106;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
class Solution {
public static int[] getCha(int[] arr2,int n){
int[] arr1 = new int[2*n];
for(int key = 0;key<2*n;key++){
arr1[key] = key;
}
int[] arr3 = new int[n];
int k = 0;
boolean flag = false;
for(int i= 0;i<arr1.length;i++){
for(int j = 0;j<arr2.length;j++){
if(arr1[i] == arr2[j]){
flag = true;
break;
}
}
if(!flag){
arr3[k] = arr1[i];
k++;
}
flag = false;
}
return arr3;
}
public static String reverse(String str){
String new_s1 = "";
for (int i = str.length() - 1; i >= 0; i--) {
new_s1 += str.charAt(i);
}
return new_s1;
}
public static int getSameCount(int a, int b) {
if(a==1){
return 1;
}else{
if(a > b) {
return a * getSameCount(a - 1, b);
}else{
return a;
}
}
}
public static List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new LinkedList<>();
boolean[] f = new boolean[n];
List<Integer> tmp = new ArrayList<>(k);
dfs(k, 0, n, f, tmp, res);
return res;
}
private static void dfs(int left, int s, int n, boolean[] f, List<Integer> tmp, List<List<Integer>> res) {
if(0 == left) {
res.add(tmp);
return;
}
for(int i = s; i < n; i++) {
if(f[i])
continue;
f[i] = true;
List<Integer> t = new ArrayList<>(tmp);
t.add(i+1);
dfs(left-1, i+1, n, f, t, res);
f[i] = false;
}
}
public long solution(int n, String s) {
int count = 0;
if(s.length() == 2 && s.substring(0,n).equals(s.substring(n,2*n))){
count = 2;
}else if(s.substring(0,n).equals(s.substring(n,2*n))){
count = getSameCount(2*n,n+1)/2;
}else {
List result = combine(2*n,n);
char[] array = s.toCharArray();
String a = "";
String b = "";
for (int i = 0; i < result.size(); i++) {
List temp = (List) result.get(i);
int[] arr2 = new int[n];
for (int j = 0; j < n; j++) {
a = a + array[(int) temp.get(j) - 1];
arr2[j] = (int) temp.get(j) - 1;
}
int[] arr3 = getCha(arr2, n);
for (int k = 0; k < n; k++) {
b = b + array[arr3[k]];
}
if (a.equals(reverse(b))) {
count++;
}
a = "";
b = "";
}
}
return count;
}
}