1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
using namespace std;

bool isPalindrome(string s) {
	string s2 = "";
	for (int i = s.length() - 1; i >= 0; i--)
		s2 += s[i];
	return s == s2;
}

string StrSwap(string s, int index1, int index2){
	char temp = s[index1];
	s[index1] = s[index2];
	s[index2] = temp;
	return s;
}

int main() {
	string s;
	cin >> s;

	if (isPalindrome(s)) {
		cout << 0 << '\n';
		return 0;
	}

	int aCount = 0;

	for (int i = 0; i < s.length(); i++)
		if (s[i] == 'a')
			aCount++;

	if (aCount % 2 == 1 && (s.length() - aCount) % 2 == 1) {
		cout << -1 << '\n';
		return 0;
	}

	long long swaps = 0;
	int right2;

	for(int left = 0, right = s.length() - 1; left < right; left++, right--) {
		
		right2 = right;
		if (s[left] != s[right]) {
			
			while(s[left] != s[right2] && right2 > left)
				right2--;
				
			if (right2 < left) {
				cout << -1 << '\n';
				return 0;
			}
			if(right2 == left){
				s = StrSwap(s,left,left+1);
				swaps++;
			}
			else{
				for(int i = right2; i < right; i++){
					s = StrSwap(s,i,i+1);
					swaps++;
				}
				
			}
			
		}
	
	}

	cout << swaps << '\n';
	return 0;
}