import java.util.Scanner;
public class Main {
public static int count = 0 ;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String str = sc.nextLine();
char[] chars = str.toCharArray();
int[] count = new int[26];//用于统计每个字母出现次数
char ch = '0';//用于存放那个出现次数为奇数的字符
int oddchar = 0 ;//统计出现次数为奇数的字符的出现次数
for(int i = 0 ; i < chars.length; i++ ){//统计每个字母出现次数
int index = chars[i] - 'a';
count[index]++;
}
for(int i = 0 ; i < 26 ; i++ ){
if(count[i] % 2 != 0){
ch = (char)(i +'a');//记录出现次数为奇数的字符
oddchar++;
}
}
if(oddchar > 1){
System.out.println("Impossible");
}else{
int result = exchange(chars, ch, n);
System.out.println(result);
}
}
public static int exchange(char[] chars , char ch,int n){
int count = 0, i,j,k;
for( i = 0 ; i < n/2 ; i++){
if(chars[i] == ch){//如果是出现次数为奇数的字符,则取对称位置的字符并从左往右遍历,寻找相同字符。
for( j = i ; j < n-1-i; j++){
if(chars[n-1-i] == chars[j]){
break;
}
}
count += j-i;
for(k = j ; k > i ; k-- ){
chars[k] = chars[k-1];
}
chars[i] = chars[j];
}else{
for(j = n-1-i; j > i; j--){
if(chars[i] == chars[j]){
break;
}
}
count += (n-i-1)-j;
for(k = j ; k < n-i-1; k++){
chars[k] = chars[k+1];
}
chars[n-1-i] = chars[i];//此处chars[j] 被它后一个元素覆盖掉了所以用chars[i]
}
}
return count;
}
}
看别人博客做出来的
地址:http://www.tuicool.com/articles/EJraqu
写的很详细