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:
from collections import deque
s = list(input())
s = deque(s)
cnt = 0
while len(s) > 1:
    left = s.popleft()
    right = s.pop()
    if left == right:continue
    if left != 'x' and right != 'x':
        print(-1)
        exit()

    if left == 'x':
        s.append(right)
    else:
        s.appendleft(left)
    cnt += 1
print(cnt)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

s = read().rstrip().decode()
ans = 0
m = len(s)
size = m // 2
cnt_ss = m - 1
cnt_s = 0
for i in range(m):
    if s[cnt_s] == s[cnt_ss]:
        if cnt_s != size:
            cnt_s += 1
        if cnt_ss != size:
            cnt_ss -= 1
    elif s[cnt_s] == 'x':
        cnt_s += 1
        ans += 1
        m += 1
    elif s[cnt_ss] == 'x':
        cnt_ss -= 1
        ans += 1
        m -= 1
    else:
        print(-1)
        exit()
    size = m // 2
    if cnt_ss == cnt_s == size:
        break
print(ans)

Submission status: Accepted

Solution code:
s=list(input())
if len(set(s))==1 and s[0]=='x':
    print(0)
    exit()

n=len(s)

nox=[i for i in s if i!='x']
if nox!=nox[::-1]:
    print(-1)
    exit()

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

Submission status: Accepted

Solution code:
s = input()

left = 0
right = len(s) - 1

cnt = 0
while left < right:
    if s[left] == s[right]:
        left += 1
        right -= 1
    elif s[left] == 'x':
        cnt += 1
        left += 1
    elif s[right] == 'x':
        cnt += 1
        right -= 1
    else:
        print(-1)
        break
else:
    print(cnt)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    s = input()
    ss = []
    for i in s:
        if i != "x":
            ss.append(i)

    if ss != ss[::-1]:
        print(-1)
    else:
        n = len(ss) + 1
        cnt = 0
        cnt_x = [0] * (n)
        pos = 0
        for i in range(len(s)):
            if s[i] == "x":
                cnt += 1

            if s[i] != "x" or i == len(s) - 1:
                cnt_x[pos] = cnt
                cnt = 0
                pos += 1

        res = 0
        for i in range(n // 2):
            res += abs(cnt_x[i] - cnt_x[-(i + 1)])

        print(res)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
from collections import deque

s = input()
n = len(s)
l = deque([])
r = deque([])
c = 0

for i in range(n):
    if s[i] != "x": l.append(s[i])
    if s[n-1-i] != "x": r.append(s[n-1-i])

if l != r:
    print(-1)
    exit(0)

if len(l) % 2 == 1: c = len(l) // 2 + 1
else: c = len(l) // 2

cntl = [0]*c
cntr = [0]*c

k = 0
i = 0

while k < c:
    if s[i] == "x":
        cntl[k] += 1
    else:
        k += 1
    i += 1

k = 0
i = n-1

while k < c:
    if s[i] == "x":
        cntr[k] += 1
    else:
        k += 1
    i -= 1

ans = 0

for j in range(c):
    ans += abs(cntl[j] - cntr[j])

print(ans)

Submission status: Accepted

Solution code:
s=input()
d=s.replace("x","")
rd=d[::-1]
if d!=rd:print(-1)
else:
    ans=0
    x,y=0,len(s)-1
    while y-x>0:
        if s[x]==s[y]:
            x+=1;y-=1
        elif s[x]=="x":
            ans+=1;x+=1
        else:
            ans+=1;y-=1
    print(ans)

Submission status: Accepted

Solution code:
# import bisect
from collections import Counter, deque # https://note.nkmk.me/python-scipy-connected-components/
# from copy import copy, deepcopy
# from functools import reduce
# from heapq import heapify, heappop, heappush
# from itertools import accumulate, permutations, combinations, combinations_with_replacement, groupby, product
# import math
# import numpy as np  # Pythonのみ！
# from operator import xor
# import re
# from scipy.sparse.csgraph import connected_components  # Pythonのみ！
# ↑cf.  https://note.nkmk.me/python-scipy-connected-components/
# from scipy.sparse import csr_matrix
# import string
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()

def resolve():
    def main():
        s=str(input())
        s=deque(iterable=s)
        cnt=0
        if len(s)==1:
            return 0
        else:
            while len(s)>=2:
                sl=s.popleft()
                sr=s.pop()
                if sl==sr:
                    continue
                elif sl!='x' and sr!='x':
                    return -1
                elif sl!='x':
                    s.appendleft(sl)
                    s.append(sr)
                    s.appendleft('x')
                    cnt+=1
                else:
                    s.append(sr)
                    s.appendleft(sl)
                    s.append('x')
                    cnt+=1
            return cnt
    print(main())









resolve()

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

s = ns()
ans = 0
r = 0
l = len(s)-1
while r < l:
  if s[r] == s[l]:
    r += 1
    l -= 1
  elif s[r] == "x":
    ans += 1
    r += 1
  elif s[l] == "x":
    ans += 1
    l -= 1
  else:
    print(-1)
    exit()

print(ans)

Submission status: Accepted

Solution code:
s = input()
n = len(s)
s_x = ''.join(s.split('x'))
for i in range(len(s_x)//2):
    if s_x[i] != s_x[-1-i]:
        print(-1)
        exit(0)
ans = 0
i = 0
j = n-1
while i < j:
    if s[i] == 'x' and s[j] == 'x':
        i += 1
        j -= 1
    elif s[i] == 'x':
        ans += 1
        i += 1
    elif s[j] == 'x':
        ans += 1
        j -= 1
    else:
        i += 1
        j -= 1
print(ans)

Submission status: Accepted

Solution code:
s = input()

l = 0
r = len(s)-1

ans = 0
flg = True
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:
        flg = False
        break

if flg: print(ans)
else: print(-1)

Submission status: Accepted

Solution code:
s = input()
len_s = len(s)
a = [i for i in s if i != "x"]
b = "".join(a)
if b != b[::-1]:
  print(-1)
  exit()
ans = 0
f,r = 0,len_s-1
while f < r:
  if s[f] == s[r]:
    f += 1
    r -= 1
  elif s[f] == "x":
    f += 1
    ans += 1
  elif s[r] == "x":
    r -= 1
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
import sys
import math  # noqa
import bisect  # noqa
import queue  # noqa


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


def main():
    S = input()

    l = 0
    r = len(S) - 1

    cnt = 0
    while l < r:
        if S[l] == S[r]:
            l += 1
            r -= 1
        elif S[l] != 'x' and S[r] == 'x':
            r -= 1
            cnt += 1
        elif S[l] == 'x' and S[r] != 'x':
            l += 1
            cnt += 1
        else:
            return print(-1)

    print(cnt)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from collections import Counter

s = input()
n = len(s)
ns = []
no = []

for i in range(n):
    if s[i] != "x":
        ns.append(s[i])
        no.append(i)
        
no = [-1] + no + [n]
        
m = len(no) 
sa = []
for i in range(m-1):
    sa.append(no[i+1] - no[i] - 1)
        
if ns != ns[::-1]:
    print(-1)
    sys.exit()
    
ans = 0
if m%2 == 1:
    mm = m//2
    te = no[mm]
    ans = 0
    for i in range(mm):
        ans += abs(sa[i]-sa[m-2-i])
else:
    mm = m//2
    te = no[mm]
    ans = 0
    for i in range(mm-1):
        ans += abs(sa[i]-sa[m-2-i])
        
print(ans)

Submission status: Accepted

Solution code:
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  s=S()
  q=collections.deque(s)

  ans=0
  while len(q)>1:
    if q[0]==q[-1]:
      q.popleft()
      q.pop()
    else:
      if q[0]=='x':
        q.append('x')
      elif q[-1]=='x':
        q.appendleft('x')
      else:
        return -1
      ans+=1
  
  return ans


# main()
print(main())

Submission status: Accepted

Solution code:
from collections import Counter

s = input()
snotx = "".join([ch for ch in s if ch != 'x'])

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

if snotx != snotx[::-1]:
    print(-1)
    exit()

# 両端から見てくる (解説解法)
index_l = 0
index_r = len(s) - 1
count = 0
while index_l < index_r:
    if s[index_l] == s[index_r]:
        index_l += 1
        index_r -= 1
    elif s[index_l] == 'x':
        count += 1
        index_l += 1
    elif s[index_r] == 'x':
        count += 1
        index_r -= 1
    else:
        print(-1)
        exit()
print(count)

Submission status: Accepted

Solution code:
from collections import Counter

s = input()
snotx = "".join([ch for ch in s if ch != 'x'])

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

if snotx != snotx[::-1]:
    print(-1)
    exit()

# 回数を合わせる
# print(s)
# print(snotx)

# xのrun-length
rl = []
i = 0
while i < len(s): 
    j = i
    while j < len(s) and s[j] == 'x':
        j += 1
    rl.append(j - i)
    i = j + 1
if s[-1] != 'x':
    rl.append(0)

# run-lengthの左右を見て合わせる
res = 0
i = 0
while i * 2 < len(rl):
    res += max(rl[i], rl[len(rl) - i - 1]) - min(rl[i], rl[len(rl) - i - 1])
    i += 1
print(res)

Submission status: Accepted

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

kb = []

for i in range(num):
    kb.append(s[i])

mae = 0
usi = num-1
ans = 0

while mae < usi:
    #print(i)
    if s[mae] != s[usi]:
        if s[mae] == 'x':
            #kb.append('x')
            ans += 1
            mae += 1
        elif s[usi] == 'x':
            #kb.insert(mae,'x')
            ans += 1
            usi -= 1
        else:
            print(-1)
            exit()
    else:
        mae += 1
        usi -= 1

print(ans)

Submission status: Accepted

Solution code:
from collections import deque
s = deque(list(input()))

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

Submission status: Accepted

Solution code:
s = input()
ans = 0
p = -1
i = 0
while i-p<len(s):
  if s[i]==s[p]:
    i += 1
    p -= 1
    continue
  elif s[i]=='x':
    i += 1
    ans += 1
  elif s[p]=='x':
    p -= 1
    ans += 1
  else:
    print(-1)
    break
else:
  print(ans)

Submission status: Accepted

Solution code:
def solve():
    S = input()
    non_x = ''
    num_x = []
    cnt = 0
    for s in S:
        if s == 'x':
            cnt += 1
        else:
            non_x += s
            num_x.append(cnt)
            cnt = 0
    num_x.append(cnt)
    if non_x != non_x[::-1]:
        return -1
    N = len(num_x)
    ans = 0
    for i in range(N):
        ans += abs(num_x[i]-num_x[-i-1])
    return ans//2
print(solve())

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()]
def I(): return int(sys.stdin.buffer.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    s = input()
    t = []
    for i,si in enumerate(s):
        if si != "x":
            t.append((i,si))
    q = [i[1] for i in t]
    if q != q[::-1]:
        print(-1)
        return
    n = len(t)
    if not n:
        print(0)
        return
    m = n >> 1
    l = t[m-(1-(n&1))][0]
    r = t[m][0]
    ans = 0
    while l >= 0 or r < len(s):
        if l < 0:
            r += 1
            ans += 1
        elif r >= len(s):
            l -= 1
            ans += 1
        elif s[l] == s[r]:
            l -= 1
            r += 1
        elif s[l] == "x":
            l -= 1
            ans += 1
        else:
            r += 1
            ans += 1
    print(ans)
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Accepted

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

def solve():
    l = 0
    r = N - 1
    cost = 0
    while l < r:
        if s[l] == s[r]:
            l += 1
            r -= 1
        elif s[l] == 'x':
            cost += 1
            l += 1
        elif s[r] == 'x':
            cost += 1
            r -= 1
        else:
            return -1
    return cost

print(solve())

Submission status: Accepted

Solution code:
s = input()
N = len(s)
s_trim = ''.join([c for c in s if c != 'x'])
N_trim = len(s_trim)

def check_anagram():
    for i in range(N_trim):
        j = N_trim - 1 - i
        if s_trim[i] != s_trim[j]:
            return False
    return True

def solve():
    if not check_anagram():
        return -1
    if N_trim == 0:
        return 0
    # Center of anagram
    pr = N_trim // 2
    pl = pr
    if N_trim % 2 == 0:
        pl -= 1

    xl = 0
    tl = 0
    while xl < N:
        if s[xl] != 'x':
            # assert s[xl] == s_trim[tl]
            if tl == pl:
                break
            tl += 1
        xl += 1

    if N_trim % 2 == 1:
        xr = xl
    else:
        xr = xl + 1
        while s[xr] == 'x':
            xr += 1

    cost = 0
    while True:
        # assert s[xl] == s_trim[pl]
        # assert s[xr] == s_trim[pr]
        # assert s[xl] == s[xr]
        # assert s_trim[pl] == s_trim[pr]
        pl -= 1; pr += 1
        while True:
            xl -= 1; xr += 1
            if not (xl >= 0 and xr < N and s[xl] == 'x' and s[xr] == 'x'):
                break
        while xl >= 0 and s[xl] == 'x':
            cost += 1
            xl -= 1
        while xr < N and s[xr] == 'x':
            cost += 1
            xr += 1
        if pl < 0 and pr >= N_trim and xl < 0 and xr >= N:
            return cost

print(solve())

Submission status: Accepted

Solution code:
import sys

s = list(input())
n = len(s)
t = []
ind = [-1]
for i in range(n):
    if s[i] != "x":
        t.append(s[i])
        ind.append(i)
ind.append(n)
# print(t)
ng = 0
lt = len(t)
for i in range(lt):
    if t[i] != t[lt-1-i]:
        ng = 1
        break
if ng == 1:
    print(-1)
    sys.exit()

ind1 = [ind[i+1]-ind[i] for i in range(len(ind)-1)]
ans = 0
for i in range(len(ind1) // 2):
    ans += abs(ind1[i] - ind1[len(ind1) - 1 - i])
print(ans)

Submission status: Accepted

Solution code:
s = input()
p = s.replace('x', '')
k = [p[i] for i in range(len(p)-1,-1,-1)]
k = "".join(k)
if k == p:
    left = 0
    right = len(s)-1
    ans = 0
    while True:
        if s[left] != s[right]:
            if s[left] == 'x':
                left += 1
                ans += 1
            else:
                right -= 1 
                ans += 1
        else:
            right -= 1
            left += 1
        if right <= left:
            break
    print(ans)
else:
    print(-1)

Submission status: Accepted

Solution code:
s = input()
l = 0
r = len(s)-1
res = 0
while l < r:
    if s[l] == s[r]:
        l += 1
        r -= 1
    elif s[l] == 'x' and s[r] != 'x':
        res += 1
        l += 1
    elif s[l] != 'x' and s[r] == 'x':
        res += 1
        r -= 1
    elif s[l] != s[r] and s[l] != 'x' and s[r] != 'x':
        print(-1)
        exit()
print(res)

Submission status: Accepted

Solution code:
def solve():
    S = input()
    N = len(S)

    left = 0
    right = N-1

    ans = 0
    while right - left > 0:
        if S[left] == S[right]:
            left += 1
            right -= 1
        else: 
            if S[left] == 'x':
                left += 1
                ans += 1
            elif S[right] == 'x':
                right -= 1
                ans += 1
            else:
                print('-1')
                return
    
    print(ans)
                
if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue
from decimal import *


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [input() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [int(input()) for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def divisor(n):
        res = []
        i = 1
        for i in range(1, int(n ** 0.5) + 1):
            if n % i == 0:
                res.append(i)
                if i != n // i:
                    res.append(n // i)
        return res

    @staticmethod
    def round_up(a, b):
        return -(-a // b)

    @staticmethod
    def is_prime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True


def pop_count(x):
    x = x - ((x >> 1) & 0x5555555555555555)
    x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
    x = x + (x >> 8)
    x = x + (x >> 16)
    x = x + (x >> 32)
    return x & 0x0000007f


MOD = int(1e09) + 7
INF = int(1e15)


def solve():
    S = list(Scanner.string())
    ans = 0
    while len(S) > 1:
        if S[0] == S[-1]:
            S.pop(0)
            S.pop(-1)
        elif S[0] == 'x':
            ans += 1
            S.pop(0)
        elif S[-1] == 'x':
            S.pop(-1)
            ans += 1
        else:
            print('-1')
            return
    print(ans)


def main():
    # sys.stdin = open("sample.txt")
    solve()


if __name__ == "__main__":
    main()

Submission status: Accepted

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

i = 0
j = N - 1
ans = 0
while i < j:
    if s[i] == s[j]:
        i += 1
        j -= 1
    elif s[i] == "x":
        ans += 1
        i += 1
    elif s[j] == "x":
        ans += 1
        j -= 1
    else:
        ans = -1
        break

print(ans)

Submission status: Accepted

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

s_wo_x = s.replace("x", "")
if s_wo_x != s_wo_x[::-1]:
    print(-1)
else:
    num_x = []
    cnt = 0
    for i in range(n):
        if s[i] == "x":
            cnt += 1
        else:
            num_x.append(cnt)
            cnt = 0
    num_x.append(cnt)

    ans = 0
    N = len(num_x)
    for i in range(N // 2):
        if num_x[i] == num_x[N - i - 1]:
            continue
        else:
            ans += abs(num_x[i] - num_x[N - i - 1])

    if N % 2 == 1:
        if num_x[N // 2] % 2 > 1 and num_x[N // 2] % 2 == 0:
            ans += 1
    print(ans)

Submission status: Accepted

Solution code:
s = input()
xlist = []
xcount = 0
t = ""
for i in range((len(s))):
    if s[i] == "x":
        xcount += 1
    else:
        xlist.append(xcount)
        xcount = 0
        t += s[i]
xlist.append(xcount)
if t != t[::-1]:
    print(-1)
else:
    ans = 0
    for i in range(len(xlist)//2):
        ans += abs(xlist[i]-xlist[-(i+1)])
    print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): return [[ini]*i for _ in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for _ in range(j)] for _ in range(k)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value

def main():
    S = input()
    l = len(S)

    T = S.replace('x', '')
    if T != T[::-1]:
        print(-1)
        exit()
    '''
    st, end = 0, l-1
    cnt = 0
    while True:
        if S[st] == S[end]:
            if st+1!=end:
                st += 1
                end -= 1
            else:
                st=end
        elif S[st] == 'x':
            st += 1
            cnt += 1
        elif S[end] == 'x':
            end -= 1
            cnt += 1
        if st==end:
            break
    print(cnt)
    '''
    zero_list = []
    cnt = 0

    for i in range(l):
        if S[i] == 'x':
            cnt += 1
        elif i>0:
            zero_list.append(cnt)
            cnt = 0
        elif i==0:
            zero_list.append(cnt)
    zero_list.append(cnt)
    '''
    #for i in range(l):
    i = 0
    while i < l:
        j = i
        while j<l and S[j]=='x':
            j += 1
        zero_list.append(j-i)
        i = j+1
    '''
    lz = len(zero_list)
    ans = 0
    for i in range(lz//2):
        ans += abs(zero_list[i] - zero_list[lz-1-i])
    print(ans)
        
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): return [[ini]*i for _ in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for _ in range(j)] for _ in range(k)]
#import bisect #bisect.bisect_left(B, a)
from collections import defaultdict #d = defaultdict(int) d[key] += value

def main():
    S = input()
    if S == S[::-1]:
        print(0)
        exit()
    l = len(S)
    T = S.replace('x', '')
    if T != T[::-1]:
        print(-1)
        exit()
    st, end = 0, l-1
    l = len(T) % 2
    cnt = 0
    while True:
        if S[st] == S[end]:
            if st+1!=end:
                st += 1
                end -= 1
            else:
                st=end
        elif S[st] == 'x':
            st += 1
            cnt += 1
        elif S[end] == 'x':
            end -= 1
            cnt += 1
        if st==end:
            break
    print(cnt)
    '''
    else:
        al = T[len(T)//2]
    pos_list = []
    for i in range(l):
        if S[i] == al:
            pos_list.append(i)
    cnt = 0
    if len(pos_list)%2 == 1:
        mid = pos_list[len(pos_list)//2]
        if mid>0:
            st = mid-1
        else:
            st = 0
        if mid<l-1:
            end = mid+1
        else:
            end = l-1
    else:
        mids = pos_list[len(pos_list)//2-1 : len(pos_list)//2+1]
        if mids[0]>0:
            st = mids[0]-1
        else:
            st = 0
        if mids[1]<l-1:
            end = mids[1]+1
        else:
            end = l-1
    flag = 0
    while True:
        if st==0 and end==l-1:
            flag = 1
        if S[st] == S[end]:
            if st > 0:
                st -= 1
            if end < l-1:
                end += 1
        elif S[st] == 'x':
            if st > 0:
                st -= 1
            cnt += 1
        elif S[end] == 'x':
            if end < l-1:
                end += 1
            cnt += 1
        if flag:
            break
    print(cnt)
    '''

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s=input()
exc_x=""
cnt=[]
now=0
for i in s:
    if i=="x":
        now+=1
    else:
        cnt.append(now)
        now=0
        exc_x+=i
cnt.append(now)
if exc_x!=exc_x[::-1]:
    print(-1)
    exit()
ans=0
n=len(cnt)
for i in range(n//2):
    ans+=abs(cnt[i]-cnt[n-i-1])
print(ans)

Submission status: Accepted

Solution code:
if __name__ == '__main__':
    s = list(input())
    rev_s = list(reversed(s))
    ans = 0
    l, r = 0, len(s) - 1

    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:
            print(-1)
            exit(0)
    print(ans)

Submission status: Accepted

Solution code:
from collections import deque
def main():

    s = deque(input())

    

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

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s=input()
l=0
r=len(s)-1
cnt=0
while(l<r):
    if s[l]==s[r]:
        l+=1
        r-=1
    elif s[l]=="x":
        cnt+=1
        l+=1
    elif s[r]=="x":
        cnt+=1
        r-=1
    else:
        cnt=-1
        break
print(cnt)

Submission status: Accepted

Solution code:
s=list(input())
s1=[]
for i in range(len(s)):
  if s[i]!="x":
    s1.append(s[i])
s2=s1[::-1]
if s1!=s2:
  print(-1)
  exit()
if s1==[]:
  print(0)
  exit()
A1=[0]*10**5
A2=[0]*10**5
i=0
j=0
while i<=len(s1)//2:
  if s[j]=="x":
    A1[i]+=1
    j=j+1
  else:
    i=i+1
    j=j+1
i=0
j=0
while i<=len(s1)//2:
  if s[-1-j]=="x":
    A2[i]+=1
    j=j+1
  else:
    i=i+1
    j=j+1
ans=0
for i in range(10**5):
  ans=ans+abs(A1[i]-A2[i])
print(ans)

Submission status: Accepted

Solution code:
S = input()
N = len(S)
l, r = 0, N-1
flg = 1
while l < r:
    while l < r and S[l] == 'x':
        l += 1
    while r > l and S[r] == 'x':
        r -= 1
    if S[l] != S[r]:
        flg = 0
        break
    l += 1
    r -= 1
if flg == 0:
    print(-1)
    exit()
l, r = 0, N-1
ans = 0
while l < r:
    if S[l] != S[r]:
        if S[l] == 'x':
            l += 1
        else:
            r -= 1
        ans += 1
    else:
        l += 1
        r -= 1
print(ans)

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/code-festival-2017-qualc/tasks/code_festival_2017_qualc_c
# xを抜いたときにその文章が回文になっていれば必ず回文にすることができる
# 回分にできる場合は両端から、文字をマッチングさせていけばxを挿入する最小回数が求められる

enu = enumerate
ra = range
s = input()
s_nx = []
for ss in s:
    if ss != 'x':
        s_nx.append(ss)

if s_nx != s_nx[::-1]:
    print(-1)
    exit()

n = (len(s_nx) + 1) // 2  # 真ん中の文字は何文字目か(1based)


# どうやったらバグらせにくい考えよう
# 各文字間に含まれるxの数をカウントして配列に入れる。あとはその配列を逆さにして差を取れば良い
s = s
x_cnt = [0]
for ss in s:
    if ss != 'x':
        x_cnt.append(0)
    else:
        x_cnt[-1] += 1
ans = 0
for a, b in zip(x_cnt, reversed(x_cnt)):
    ans += abs(a - b)


# print(x_cnt)
print(ans // 2)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

s = input()
cnt_1 = 0
cnt_2 = len(s) - 1
ans = 0
m = len(s)
end = m // 2
for i in range(cnt_2 + 1):
    if s[cnt_1] == s[cnt_2]:
        if end != cnt_1:
            cnt_1 += 1
        if end != cnt_2:
            cnt_2 -= 1
    elif s[cnt_1] == 'x':
        cnt_1 += 1
        ans += 1
        m += 1
    elif s[cnt_2] == 'x':
        cnt_2 -= 1
        ans += 1
        m -= 1
    else:
        print(-1)
        exit()
    end = m // 2
    if end == cnt_1 and end == cnt_2:
        break
print(ans)

Submission status: Accepted

Solution code:
from collections import deque

s = deque(input())
ans = 0
while s:
    L = s[0]
    R = s[-1]
    if L == R:
        if 1 == len(s):
            break
        L = s.popleft()
        R = s.pop()
        continue
    elif L == 'x' and R != 'x':
        ans += 1
        s.append('x')
    elif L != 'x' and R == 'x':
        ans += 1
        s.appendleft('x')
    elif L != 'x' and R != 'x':
        ans = -1
        break
print(ans)

Submission status: Accepted

Solution code:
s = input()
L = 0
R = len(s)-1
ans = 0
while L < R:
    if s[L] == s[R]:
        L += 1
        R -= 1
    elif s[L] == 'x' and s[R] != 'x':
        ans += 1
        L += 1
    elif s[L] != 'x' and s[R] == 'x':
        ans += 1
        R -= 1
    elif s[L] != s[R] and s[L] != 'x' and s[R] != 'x':
        ans = -1
        break
print(ans)

Submission status: Accepted

Solution code:
from collections import deque

s = input()
s2 = s.replace('x', '')
if s2 != s2[::-1]:
    print(-1)
else:
    d = deque(s)
    a, b = [], []
    cnt = 0
    x = y = ''
    x_skip = y_skip = 0
    while d:
        if not x_skip:
            x = d.popleft()
        if 0 < len(d)and not y_skip:
            y = d.pop()

        if y == '':
            break

        if x == y != 'x':
            cnt += abs(len(a)-len(b))
            x = y = ''
            a, b = [], []
            x_skip = y_skip = 0
            continue

        if x == 'x':
            a.append(x)
        else:
            x_skip = 1

        if y == 'x':
            b.append('x')
        else:
            y_skip = 1
    else:
        cnt += abs(len(a)-len(b))

    print(cnt)