def not_possible(word: str) -> bool:
a = word.count('a')
b = word.count('b')
return (a % 2 == 1) and (b % 2 == 1)
def count_moves(word: list[chr]) -> int:
if len(word) <= 1:
return 0
if word[0] == word[-1]:
return count_moves(word[1:-1])
first_left = ''.join(word[1:]).find(word[-1]) + 1
first_right = ''.join(word[::-1][1:]).find(word[0]) + 1
if first_left != -1 and first_left < first_right:
word[0], word[first_left] = word[first_left], word[0]
return first_left + count_moves(word[1:-1])
else:
word[-1], word[-1-first_right] = word[-1-first_right], word[-1]
return first_right + count_moves(word[1:-1])
data = input()
if not_possible(data):
print(-1)
else:
print(count_moves(list(data)))
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 | def not_possible(word: str) -> bool: a = word.count('a') b = word.count('b') return (a % 2 == 1) and (b % 2 == 1) def count_moves(word: list[chr]) -> int: if len(word) <= 1: return 0 if word[0] == word[-1]: return count_moves(word[1:-1]) first_left = ''.join(word[1:]).find(word[-1]) + 1 first_right = ''.join(word[::-1][1:]).find(word[0]) + 1 if first_left != -1 and first_left < first_right: word[0], word[first_left] = word[first_left], word[0] return first_left + count_moves(word[1:-1]) else: word[-1], word[-1-first_right] = word[-1-first_right], word[-1] return first_right + count_moves(word[1:-1]) data = input() if not_possible(data): print(-1) else: print(count_moves(list(data))) |
English