6
aaabbb
ab
abc
mnop
xyyx
xaxbbbxx

3
1
-1
2
0
1

參考答案

```import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

public class Solution {

public static void main(final String[] args) {
final Scanner sc = new Scanner(System.in);

int t = Integer.parseInt(sc.nextLine());
while (t-- > 0) {
final String s = sc.nextLine();
final int length = s.length();
if (length % 2 != 0) {
System.out.println(-1);
} else {
int count = 0;
final int length_half = length / 2;
final char[] a = s.subSequence(0, length_half).toString().toCharArray();
final char[] b = s.subSequence(length_half, length).toString().toCharArray();
final HashMap<Character, Integer> mapA = createMap(a);
final HashMap<Character, Integer> mapB = createMap(b);
final Set<Character> keys = mapB.keySet();
for (final Character c : keys) {
final int countB = mapB.get(c);
if (mapA.containsKey(c)) {
final int countA = mapA.get(c);
if(countB > countA){
count += countB - countA;
}
} else {
count += countB;
}
}
System.out.println(count);
}
}
}

public static HashMap<Character, Integer> createMap(final char[] s) {
final HashMap<Character, Integer> map = new HashMap<>();
final int length = s.length;
for (int i = 0; i < length; ++i) {
final char c = s[i];
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
return map;
}
}```