Problem:


Score : 400 points

Problem Statement

We have a string s consisting of lowercase English letters.
Snuke can perform the following operation repeatedly:

Insert a letter x to any position in s of his choice, including the beginning and end of s.

Snuke's objective is to turn s into a palindrome.
Determine whether the objective is achievable. If it is achievable, find the minimum number of operations required.

Notes

A palindrome is a string that reads the same forward and backward.
For example, a, aa, abba and  abcba are palindromes, while ab, abab and abcda are not.

Constraints

1 \leq |s| \leq 10^5

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

If the objective is achievable, print the number of operations required.
If it is not, print -1 instead.

Sample Input 1

xabxa

Sample Output 1

2

One solution is as follows (newly inserted x are shown in bold):

xabxa → xaxbxa → xaxbxax

Sample Input 2

ab

Sample Output 2

-1

No sequence of operations can turn s into a palindrome.

Sample Input 3

a

Sample Output 3

0

s is a palindrome already at the beginning.

Sample Input 4

oxxx

Sample Output 4

3

One solution is as follows:

oxxx → xoxxx → xxoxxx → xxxoxxx



Sample input:
xabxa


Sample output:
2

Submission status: Accepted

Solution code:
s = input()

ans = 0

while s:

    # 先頭と末尾が同じ場合
    if s[0] == s[-1]:
        s = s[1:-1]

    ##### 以下、先頭と末尾が異なる場合の分類 #####

    # 先頭がxの場合
    elif s[0] == 'x':
        # 仮想的に末尾にxを足す
        s = s[1:]
        ans += 1

    # 末尾がxの場合
    elif s[-1] == 'x':
        # 仮想的に先頭にxを足す
        s = s[:-1]
        ans += 1

    # 先頭も末尾もxではない場合
    else:
        print(-1)
        exit()

print(ans)

Submission status: Accepted

Solution code:


def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    from collections import deque
    s=list(input())
    dq=deque(s)
    
    ans=0
    while len(dq)>=2:
        l=dq.popleft()
        r=dq.pop()
        if l==r:
            pass
        elif l=="x":
            ans+=1
            dq.append(r)
        elif r=="x":
            ans+=1
            dq.appendleft(l)
        else:
            print(-1)
            exit()
            
    print(ans)

main()

Submission status: Accepted

Solution code:
import sys
s=input()
b=[]
an=0
for i in range(len(s)):
  if s[i]!="x":
    b.append(s[i])
for i in range(len(b)):
  if b[i]!=b[-i-1]:
    print(-1)
    sys.exit()

i=j=0 
while i<=len(s)-1-j:
  if s[i]==s[-1-j]:
    i+=1
    j+=1
  elif s[i]=="x":
    i+=1
    an+=1
  elif s[-1-j]=="x":
    j+=1
    an+=1

print(an)

Submission status: Accepted

Solution code:
s = input()
N = len(s)

j = N-1
xi = 0
xj = 0
res = 0
for i in range(N):
    if s[i] == 'x':
        xi += 1
        continue
    while j>=i:
        if s[j] == 'x':
            xj += 1
            j -= 1
            continue

        if s[i] != s[j]:
            print(-1)
            exit()
        res += abs(xj-xi)
        j -= 1
        break
    xi = xj = 0
print(res)

Submission status: Accepted

Solution code:
from math import ceil,floor,comb,factorial,gcd,pow,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

s = input()

i = 0
ans = 0
while s:
    if s[0] == s[-1]:
        s = s[1:-1]
    elif s[0] == 'x':
        s = s[1:]
        ans += 1
    elif s[-1] == 'x':
        s = s[:-1]
        ans += 1
    else:
        print(-1)
        exit()
print(ans)

Submission status: Accepted

Solution code:
from math import ceil,floor,comb,factorial,gcd,pow,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

s = input()

i = 0
j = len(s)-1
ans = 0
while i <= j:
    if s[i] == 'x' and s[j] != 'x':
        while i <= j and s[i] == 'x':
            ans += 1
            i += 1
    elif s[j] == 'x' and s[i] != 'x':
        while i <= j and s[j] == 'x':
            ans += 1
            j -= 1

    if i <= j:
        if s[i] != s[j]:
            print(-1)
            exit()
        i += 1
        j -= 1
    else:
        break

print(ans)

Submission status: Accepted

Solution code:
s = input()

s1 = s.replace('x', '')

# 先に回文にできないケースを除外する
if s1 != s1[::-1]:
    print(-1)
    exit()

l, r = 0, len(s)-1
ans = 0
while l < r:
    if s[l] == s[r]:
        l += 1
        r -= 1
    elif s[l] == 'x':
        l += 1
        ans += 1
    elif s[r] == 'x':
        r -= 1
        ans += 1
    else:
        AssertionError('ここには来ないはず')
        pass

print(ans)

Submission status: Accepted

Solution code:
S = input()
ans = 0
while len(S)>=2:
    if S[0]==S[-1]:
        S = S[1:-1]
    elif S[0]=='x':
        ans += 1
        S = S[1:]
    elif S[-1]=='x':
        ans += 1
        S = S[:-1]
    else:
        ans = -1
        break
print(ans)

Submission status: Accepted

Solution code:
string = input()
l_idx = 0
r_idx = len(string) - 1
ans = 0
while l_idx <= r_idx:
    l = string[l_idx]
    r = string[r_idx]
    if l == r:
        l_idx += 1
        r_idx -= 1
    else:
        if l == 'x':
            l_idx += 1
            ans += 1
        elif r == 'x':
            r_idx -= 1
            ans += 1
        else:
            print(-1)
            exit()
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
def m():
    S = input()
    N = len(S)

    q = deque(S)
    ans = 0
    while len(q) > 1:
        left,right = q[0], q[-1]
        if left == right:
            q.pop()
            q.popleft()
            continue
        if left == 'x':
            q.popleft()
            ans +=1
            continue
        if right == 'x':
            ans +=1
            q.pop()
            continue
        return -1
    return ans


print(m())

Submission status: Accepted

Solution code:
import sys
import itertools
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: map(int, read().split())
in_s = lambda: readline().rstrip().decode('utf-8')


def main():

    s = in_s()

    if s == s[::-1]:
        print(0)
        exit()

    t = s.replace('x', '')
    if t != t[::-1]:
        print(-1)
        exit()

    f = (s[0] == 'x')
    xnum = []
    count = 0
    s = s + 'a'
    N = len(s)

    for i in range(N):
        if s[i] == 'x':
            if f:
                count += 1
            else:
                count = 1
            f = True
        else:
            if f:
                xnum.append(count)
                count = 0
            else:
                xnum.append(0)
            f = False

    ans = 0
    xn = len(xnum)
    for i in range(xn // 2):
        ans += abs(xnum[i] - xnum[xn - 1 - i])

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

s = deque(input())

ans = 0
while len(s) > 1:
    if s[0] == s[-1]:
        s.pop()
        s.popleft()
    elif s[0] == 'x':
        s.popleft()
        ans += 1
    elif s[-1] == 'x':
        s.pop()
        ans += 1
    elif s[0] != s[-1]:
        print(-1)
        break
else:
    print(ans)

Submission status: Accepted

Solution code:
from collections import deque

s = deque(input())

ans = 0
while len(s) > 1:
    if s[0] == s[-1]:
        s.pop()
        s.popleft()
    elif s[0] == 'x':
        s.popleft()
        ans += 1
    elif s[-1] == 'x':
        s.pop()
        ans += 1
    else:
        print(-1)
        break
else:
    print(ans)

Submission status: Accepted

Solution code:
s = list(input())
swox = []
xnum = []

count = 0
for i in range(len(s)):
    if s[i] != 'x':
        swox.append(s[i])
        xnum.append(count)
        count = 0
    if s[i] == 'x':
        count += 1

xnum.append(count)

for i in range(len(swox)//2):
    if swox[i] != swox[-i-1]:
        print(-1)
        exit()

if len(swox) == 0 or sum(xnum) == 0:
    print(0)
else:
    ans = 0
    for i in range(len(xnum)//2):
        ans += abs(xnum[i]-xnum[-i-1])
    print(ans)

Submission status: Accepted

Solution code:
s=list(input())
n=len(s)

if n==1:
    print(0)
    exit(0)
from collections import deque

d=deque(s)
i=0
j=1
cnt=0
while d:
    f=d[0]
    l=d[-1]
    if f==l:
        d.popleft()
        if len(d)==0:
            break
        d.pop()
    else:
        if f=='x' and l!='x':
            cnt+=1
            d.popleft()
        elif f!='x' and l=='x':
            cnt+=1
            d.pop()
        else:
            print(-1)
            exit(0)

print(cnt)

Submission status: Accepted

Solution code:
s = list(input())
ans = 0
while len(s) > 1:
    if s[0] == s[-1]:
        del s[0]
        del s[-1]
    else:
        if s[0] == "x":
            del s[0]
            ans += 1
        elif s[-1] == "x":
            del s[-1]
            ans += 1
        else:
            print(-1)
            exit()
print(ans)

Submission status: Accepted

Solution code:
s = input()

core = []

for c in s:
    if c != 'x':
        core.append(c)
if core == []:
    print(0)
    exit()
l = 0
r = len(core) - 1

while l <= r:
    if core[l] != core[r]:
        print(-1)
        exit()
    l += 1
    r -= 1

ans = 0
l = 0
r = len(s) - 1

while l <= r:
    lx = 0
    rx = 0
    while s[l] == 'x':
        l += 1
        lx += 1
    while s[r] == 'x':
        r -= 1
        rx += 1
    ans += abs(lx - rx)
    l += 1
    r -= 1
print(ans)

Submission status: Accepted

Solution code:
def main():
    s = input()
    l, r = 0, len(s) - 1
    ans = 0
    while r > l:
        if s[l] == s[r]:
            l += 1
            r -= 1
        else:
            if s[l] == 'x':
                l += 1
            elif s[r] == 'x':
                r -= 1
            else:
                print(-1)
                exit()
            ans += 1
    print(ans)



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    s = SS()

    s_x = [i for i in s if i != 'x']
    l_s_x = len(s_x)
    for i in range(l_s_x):
        if s_x[i] != s_x[l_s_x-1-i]:
            print(-1)
            return

    x_num = []
    cnt = 0
    for i in s:
        if i == 'x':
            cnt += 1
        else:
            x_num.append(cnt)
            cnt = 0
    if s[-1] == 'x':
        x_num.append(cnt)
    else:
        x_num.append(0)

    len_x_num = len(x_num)
    ans = 0
    for i in range(len_x_num):
        ans += max(x_num[len_x_num-1-i] - x_num[i], 0)

    print(ans)

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    s = SS()

    s_x = [i for i in s if i != 'x']
    l_s_x = len(s_x)
    for i in range(l_s_x):
        if s_x[i] != s_x[l_s_x-1-i]:
            print(-1)
            return

    x_num = []
    cnt = 0
    for i in s:
        if i == 'x':
            cnt += 1
        else:
            x_num.append(cnt)
            cnt = 0
    if s[-1] == 'x':
        x_num.append(cnt)
    else:
        x_num.append(0)

    ans = 0
    for i in range(len(x_num)):
        ans += max(x_num[len(x_num)-1-i] - x_num[i], 0)

    print(ans)

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
from typing import Any, Callable, Deque, Dict, List, Mapping, Optional, Sequence, Set, Tuple, TypeVar, Union
# import time
# import math, cmath
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import _heapify_max, _heappop_max, _siftdown_max
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import Fraction               # Fraction(a, b) => a / b ∈ Q. note: Fraction(0.1) do not returns Fraciton(1, 10). Fraction('0.1') returns Fraction(1, 10)



def main():
    Num = Union[int, float]
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79e+308
    # inf = 2 ** 63 - 1             # (for fast JIT compile in PyPy) 9.22e+18
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def isp():   return input().split()
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    def debug(x):print(x, file=sys.stderr)
    # def _heappush_max(h, item): h.append(item); _siftdown_max(h, 0, len(h)-1)
    
    def check_palindrome(s):
        n = len(s)
        for i in range(n//2):
            if s[i] != s[n-1-i]:
                return False
        return True
    
    def find_center(s, cnt):
        num = 0
        n = len(s)
        for i in range(n):
            if s[i] != 'x':
                num += 1
            if num == cnt:
                return i

    def find_center_even(s, cnt):
        num = 0
        n = len(s)
        left, right = -1, -1
        for i in range(n):
            if s[i] != 'x':
                num += 1     
            if num == cnt:
                if left == -1:
                    left = i
                    debug(f"left {left}")
            if num == cnt + 1:
                right = i
                debug(f"right {right}")
                return (left + right) / 2
    
    def not_x_split(s):
        buf = []
        s += 'E'
        n = len(s)
        x_cnt = 0
        for i in range(n):
            if s[i] != 'x':
                buf.append(x_cnt)
                x_cnt = 0
            else:
                x_cnt += 1
        return buf



    def solve(s, buf):
        bufsize = len(buf)
        if bufsize % 2 == 0:
            cnt = bufsize // 2
            ind = find_center_even(s, cnt)
        else:
            cnt = (bufsize + 1) // 2
            ind = find_center(s, cnt)
        
        if ind % 1 == 0:
            left_s = s[:int(ind)][::-1]
            right_s = s[int(ind)+1:]
        else:
            left_s = s[:int(ind)+1][::-1]
            right_s = s[int(ind)+1:]

        # print(f"ind {ind}")
        # print(left_s)
        # print(right_s)
        left = not_x_split(left_s)
        right = not_x_split(right_s)
        # print(left)
        # print(right)
        assert len(left) == len(right)
        ans = 0
        for i in range(len(left)):
            ans += max(left[i], right[i]) - min(left[i], right[i])
        return ans

    
    s = input()
    if check_palindrome(s):
        print(0)
    else:
        buf = [char for char in s if char != 'x']
        if not check_palindrome(buf):
            print(-1)
        else:
            # print('solve')
            print(solve(s, buf))



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
from typing import Any, Callable, Deque, Dict, List, Mapping, Optional, Sequence, Set, Tuple, TypeVar, Union
# import time
# import math, cmath
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import _heapify_max, _heappop_max, _siftdown_max
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import Fraction               # Fraction(a, b) => a / b ∈ Q. note: Fraction(0.1) do not returns Fraciton(1, 10). Fraction('0.1') returns Fraction(1, 10)



def main():
    Num = Union[int, float]
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79e+308
    # inf = 2 ** 63 - 1             # (for fast JIT compile in PyPy) 9.22e+18
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def isp():   return input().split()
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    # def _heappush_max(h, item): h.append(item); _siftdown_max(h, 0, len(h)-1)
    
    def check_palindrome(s):
        n = len(s)
        for i in range(n//2):
            if s[i] != s[n-1-i]:
                return False
        return True
    
    def find_center(s, cnt):
        num = 0
        n = len(s)
        for i in range(n):
            if s[i] != 'x':
                num += 1
            if num == cnt:
                return i

    def find_center_even(s, cnt):
        num = 0
        n = len(s)
        left, right = -1, -1
        for i in range(n):
            if s[i] != 'x':
                num += 1     
            if num == cnt:
                if left == -1:
                    left = i
                    # print(f"left {left}")
            if num == cnt + 1:
                right = i
                # print(f"right {right}")
                return (left + right) / 2
    
    def not_x_split(s):
        buf = []
        s += 'E'
        n = len(s)
        x_cnt = 0
        for i in range(n):
            if s[i] != 'x':
                buf.append(x_cnt)
                x_cnt = 0
            else:
                x_cnt += 1
        return buf



    def solve(s, buf):
        bufsize = len(buf)
        if bufsize % 2 == 0:
            cnt = bufsize // 2
            ind = find_center_even(s, cnt)
        else:
            cnt = (bufsize + 1) // 2
            ind = find_center(s, cnt)
        
        if ind % 1 == 0:
            left_s = s[:int(ind)][::-1]
            right_s = s[int(ind)+1:]
        else:
            left_s = s[:int(ind)+1][::-1]
            right_s = s[int(ind)+1:]

        # print(f"ind {ind}")
        # print(left_s)
        # print(right_s)
        left = not_x_split(left_s)
        right = not_x_split(right_s)
        # print(left)
        # print(right)
        assert len(left) == len(right)
        ans = 0
        for i in range(len(left)):
            ans += max(left[i], right[i]) - min(left[i], right[i])
        return ans

    
    s = input()
    if check_palindrome(s):
        print(0)
    else:
        buf = [char for char in s if char != 'x']
        if not check_palindrome(buf):
            print(-1)
        else:
            # print('solve')
            print(solve(s, buf))



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
S = input()

i = 0
j = len(S) - 1
res = 0
while i < j:
    if S[i] == S[j]:
        i += 1
        j -= 1
    elif S[i] == 'x':
        res += 1
        i += 1
    elif S[j] == 'x':
        res += 1
        j -= 1
    else:
        print(-1)
        exit()

print(res)

Submission status: Accepted

Solution code:
import sys


def input():
    return sys.stdin.readline().strip()


sys.setrecursionlimit(20000000)

MOD = 10 ** 9 + 7
INF = float("inf")


def main():
    S = input()
    answer = 0
    while S:
        if S[0] == S[-1]:
            S = S[1:-1]
        elif S[0] == "x":
            S = S + "x"
            answer += 1
        elif S[-1] == "x":
            S = "x" + S
            answer += 1
        else:
            print(-1)
            return
    print(answer)


if __name__ == "__main__":
    main()