s = list(input()) n = len(s) z = [] o = [] for i in range(n): z.append(i) if s[i] == 'a' else o.append(i) c=0 for i in range(n//2): if s[i] != s[n-i-1]: a = o[0]-i if s[i] == 'a' else z[0] -i b = n-1-i-o[-1] if s[n-i-1] == 'a' else n-i-1-z[-1] if a<b: if s[i] == 'a': s[z[0]], s[o[0]]=s[o[0]], s[z[0]] z[0]=o[0] o.pop(0) else: s[o[0]], s[z[0]]=s[z[0]], s[o[0]] o[0] = z[0] z.pop(0) if s[n-i-1] == 'a': z.pop() else: o.pop() c+=a else: if s[n-i-1] == 'b': s[o[-1]], s[z[-1]]=s[z[-1]], s[o[-1]] o[-1]=z[-1] z.pop() else: s[z[-1]], s[o[-1]]=s[o[-1]], s[z[-1]] z[-1]=o[-1] o.pop() if s[i] == 'a': z.pop(0) else: o.pop(0) c+=b else: if s[i] == 'a': z.pop(0) else: o.pop(0) if s[n-i-1] == 'a': z.pop() else: o.pop() ok = 1 for i in range(n//2): if s[i] != s[n-i-1]: ok =0 break print(c) if ok == 1 else print(-1)
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 | s = list(input()) n = len(s) z = [] o = [] for i in range(n): z.append(i) if s[i] == 'a' else o.append(i) c=0 for i in range(n//2): if s[i] != s[n-i-1]: a = o[0]-i if s[i] == 'a' else z[0] -i b = n-1-i-o[-1] if s[n-i-1] == 'a' else n-i-1-z[-1] if a<b: if s[i] == 'a': s[z[0]], s[o[0]]=s[o[0]], s[z[0]] z[0]=o[0] o.pop(0) else: s[o[0]], s[z[0]]=s[z[0]], s[o[0]] o[0] = z[0] z.pop(0) if s[n-i-1] == 'a': z.pop() else: o.pop() c+=a else: if s[n-i-1] == 'b': s[o[-1]], s[z[-1]]=s[z[-1]], s[o[-1]] o[-1]=z[-1] z.pop() else: s[z[-1]], s[o[-1]]=s[o[-1]], s[z[-1]] z[-1]=o[-1] o.pop() if s[i] == 'a': z.pop(0) else: o.pop(0) c+=b else: if s[i] == 'a': z.pop(0) else: o.pop(0) if s[n-i-1] == 'a': z.pop() else: o.pop() ok = 1 for i in range(n//2): if s[i] != s[n-i-1]: ok =0 break print(c) if ok == 1 else print(-1) |