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
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

bool isPalindrome(string s){
    for(ll i = 0; i < s.size()/2; i++){
        if(s[i] != s[s.size() - i - 1]){
            return false;
        } 
    }
    return true;
}

bool couldBeAPalindrome(string s){
    pair<int, int> result = {count(s.begin(), s.end(), 'a')%2, count(s.begin(), s.end(), 'b')%2};
    if(s.size()%2 == 0 && !result.first && !result.second) return true;
    else if(s.size()%2 != 0 && ((result.first && !result.second) || (!result.first || result.second))) return true;
    else return false;
}

ll n_of_changes(string s, ll curr_n = 0, ll id = 0){
    if(isPalindrome(s)){
        return curr_n;
    }
    ll total_n = LONG_MAX, i = id;
    while(i < s.size() - 1){
        if(s[i] != s[i+1]){
            string new_s = s;
            swap(new_s[i], new_s[i+1]);
            total_n = min(total_n, n_of_changes(new_s, curr_n+1, i+1));
        }
        i++;
    }
    return total_n;
}

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    string s;
    cin >> s;

    (couldBeAPalindrome(s)) ? cout << n_of_changes(s) : cout << -1;

    return 0;
}