#include <bits/stdc++.h> using namespace std; int main(){ string s, s1; cin >> s; s1 = s; int a = 0, b = 0; for(int i = 0; i < s.length(); i++){ if(s[i] == 'a') a++; else b++; } if(b%2 == 1 && a % 2 == 1){ cout << "-1"; return 0; } int l = 0, r = s.length() - 1, ans = 0; while(l < r){ if(s[l] == s[r]){ l++; r--; } else{ int left = l+1; int right = r-1; while(left <= r){ if(s[left] == s[r]){ break; } left++; } while(right >= l){ if(s1[right] == s1[l]){ break; } right--; } if(left - l < r - right){ ans += left - l; s[left] = s[l]; s[l] = s[r]; } else{ ans += r - right; s[right] = s[r]; s[r] = s[l]; } l++; r--; } } cout << ans; return 0; } // baaabba -> baaabab // 0123456 // abaaabbaababa // 0123456
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 | #include <bits/stdc++.h> using namespace std; int main(){ string s, s1; cin >> s; s1 = s; int a = 0, b = 0; for(int i = 0; i < s.length(); i++){ if(s[i] == 'a') a++; else b++; } if(b%2 == 1 && a % 2 == 1){ cout << "-1"; return 0; } int l = 0, r = s.length() - 1, ans = 0; while(l < r){ if(s[l] == s[r]){ l++; r--; } else{ int left = l+1; int right = r-1; while(left <= r){ if(s[left] == s[r]){ break; } left++; } while(right >= l){ if(s1[right] == s1[l]){ break; } right--; } if(left - l < r - right){ ans += left - l; s[left] = s[l]; s[l] = s[r]; } else{ ans += r - right; s[right] = s[r]; s[r] = s[l]; } l++; r--; } } cout << ans; return 0; } // baaabba -> baaabab // 0123456 // abaaabbaababa // 0123456 |