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: Time Limit Exceeded

Solution code:
n = input()

nc = n.replace("x","")

ncr = nc[::-1]

ans = -1

if ncr == nc:
    ans =0
    nl = list(n)
    i = 0
    j = 0
    while(1):
        if i >= len(nl)-(j+1):break
        while(1):
            if i > len(nl)-1 :break
            if nl[i] == "x":
                i += 1
            else:
                if nl[-(i+1)] == nl[i]:
                    i += 1
                else:
                    break
        while(1):
            if j > len(nl)-1: break
            if nl[len(nl)-(j+1)] == "x":
                j += 1
            else :
                if nl[len(nl)-(j+1)] == nl[j]:
                    j += 1
                else:
                    break
        if i > j :
            nl.insert(len(nl)-j,"x")
            ans += 1
            i = j
        if i < j :
            nl.insert(i,"x")
            j = i
            ans += 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def i1():
 return int(input())
def i2():
 return [int(i) for i in input().split()]
s=input()
ss=s.replace("x","")
if ss!=ss[::-1]:
 print(-1)
else:
 e=[]
 for i in range(len(ss)):
  e.append(ss[i])
 j=0
 k=0
 d1=[]
 jj=0
 kk=0
 d2=[]
 for i in range(len(s)):
  if k<len(e) and s[i]==e[k] :
    d1.append(s[j:i])
    j=i+1
    k+=1
  if kk<len(e) and s[::-1][i]==e[kk] :
    d2.append(s[::-1][jj:i])
    jj=i+1
    kk+=1
 d1.append(s[j:])
 d2.append(s[::-1][jj:]) 
 dd=0  
 for i in range(len(d1)):
   dd+=abs(len(d1[i])-len(d2[i]))
 print(dd//2)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Here your code !
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct  9 22:12:40 2017

@author: kitagenbakurou
"""
import numpy as np
import copy

def insert(pos, s, x):
  return x.join([s[:pos], s[pos:] ])

s = input()
N = len(s)

i = 0
cnt = 0
flag = True
while i < N - i - 1 : 
    if s[i] != s[N - i - 1] : 
        if s[i] == "x" : 
            cnt += 1
            s = insert(N - i  , s , "x")
        elif s[N - i - 1] == "x" : 
            cnt += 1
            s = insert(i , s , "x")
        else : 
            flag = False
            break
    N = len(s)
    i += 1

if flag : 
    print(cnt)
else : 
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import copy
s = list(input())
check = [s[i] for i in range(len(s))]



for i in range(s.count("x")):
    check.remove("x")

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

ans = 0
first = 0
latter = 0
i = 0
while i<(len(s)+first+latter)//2:
    if s[i-first]!=s[-1+(-1)*i+latter]:
        ans += 1
        if s[i-first]=="x":
            latter += 1
        else:
            first += 1
    i += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Here your code !
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct  9 22:12:40 2017

@author: kitagenbakurou
"""
import numpy as np
import copy

def insert(pos, s, x):
  return x.join([s[:pos], s[pos:] ])

s = input()
N = len(s)

i = 0
cnt = 0
flag = True
while i < N - i - 1 : 
    if s[i] != s[N - i - 1] : 
        if s[i] == "x" : 
            cnt += 1
            s = insert(N - i  , s , "x")
            i = -1
        elif s[N - i - 1] == "x" : 
            cnt += 1
            s = insert(i , s , "x")
            i = -1
        else : 
            flag = False
            break
    N = len(s)
    i += 1

if flag : 
    print(cnt)
else : 
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
s = input()
S = s.replace("x", "")
judge = 0

if len(s) == 1:
    judge = 5

if judge != 5:
    for i in range(len(S)):
        if S[i] != S[-(i+1)]:
            judge = 1
            break

s_ = []
for i in range(len(s)):
    s_.append(s[i])

ans = 0

if s_[0] == "x" and s_[-1] != "x":
    s_.append("x")
    ans += 1
if s_[0] != "x" and s_[-1] == "x":
    s_.insert(0, "x")
    ans += 1

if judge == 0:
    i = 1
    while judge == 0:
        if s_[i] != s_[-(i+1)]:
            if s_[i] == "x":
                s_.insert(-i, "x")
                ans += 1
            else:
                s_.insert(i, "x")
                ans += 1
        i += 1
        if i == len(s_):
            judge = 2

if judge == 2:
    print(ans)
elif judge == 5:
    print(0)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:

s = list(input())
s2 = s.copy()

for i in range(len(s2)):
    if "x" in s2:
        s2.remove("x")
        
def cycle_check(S , level):
    
    # 回文になっているかどうかのみ
    if level == 1:
        for i in range(len(S)//2):
            if S[i] != S[-i-1]:
                return True
        else:
            return False
    
    # 必要なxの個数
    if level == 2:
        x_cnt = 0
        x_list = []
        for s in S:
            if s != "x":
                if x_cnt > 0:
                    x_list.append(x_cnt)
                x_list.append(0)
                x_cnt = 0
            else:
                x_cnt += 1
        
        if x_cnt > 0:
            x_list.append(x_cnt)
        
        ans = 0
        for i in range(len(x_list)//2):
            ans += abs(x_list[i]-x_list[-i-1])
            
        return ans
    
if cycle_check(s2,1):
    print(-1)

else:
    print(cycle_check(s, 2))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
s = input()
s_list = [i for i in s]
s_without_x = [i for i in s_list if i != "x"]

if s_without_x != s_without_x[::-1]:
    print(-1)
else:
    kw_count = len(s_without_x)
    left_count_list = []
    right_count_list = []
    if kw_count % 2 == 0:
        half_s_wox_left = s_without_x[:int(kw_count/2)]
        s_ar = np.array(s_list)
        for i in range(len(half_s_wox_left)):
            count = np.min(np.where(s_ar == half_s_wox_left[i]))
            left_count_list.append(count)
            s_ar = s_ar[count+1:]
            
        half_s_wox_right = s_without_x[int(kw_count/2):]
        s_ar_back = np.array(s_list[::-1])
        half_s_wox_right_back = half_s_wox_right[::-1]
        for i in range(len(half_s_wox_right_back)):
            count = np.min(np.where(s_ar_back == half_s_wox_right_back[i]))
            right_count_list.append(count)
            s_ar_back = s_ar_back[count+1:]
            
        sousa_count = 0
        for i in range(len(left_count_list)):
            sousa_count += np.abs(left_count_list[i] - right_count_list[i])
        
        print(sousa_count)
    else:
        half_s_wox_left = s_without_x[:int(kw_count//2+1)]
        s_ar = np.array(s_list)
        for i in range(len(half_s_wox_left)):
            count = np.min(np.where(s_ar == half_s_wox_left[i]))
            left_count_list.append(count)
            s_ar = s_ar[count+1:]
            
        half_s_wox_right = s_without_x[int(kw_count//2):]
        s_ar_back = np.array(s_list[::-1])
        half_s_wox_right_back = half_s_wox_right[::-1]
        for i in range(len(half_s_wox_right_back)):
            count = np.min(np.where(s_ar_back == half_s_wox_right_back[i]))
            right_count_list.append(count)
            s_ar_back = s_ar_back[count+1:]
            
        sousa_count = 0
        for i in range(len(left_count_list)):
            sousa_count += np.abs(left_count_list[i] - right_count_list[i])
        
        print(sousa_count)

Submission status: Time Limit Exceeded

Solution code:
import copy
s = list(input())
check = copy.deepcopy(s)

for i in range(s.count("x")):
    check.remove("x")

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

ans = 0
first = 0
latter = 0
i = 0
while i<(len(s)+first+latter)//2:
    if s[i-first]!=s[-1+(-1)*i+latter]:
        ans += 1
        if s[i-first]=="x":
            latter += 1
        else:
            first += 1
    i += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
S = input()
n = 0
s = []
patern = 0
for i in range(len(S)):
    s.append(S[i])
while n < len(s)//2+1:
    if s[n] is 'x':
        if s[-n-1] is not 'x':
            s.append('x')
            patern += 1
    else:
        if s[-n-1] is 'x':
            s.insert(n,'x')
            patern += 1
        elif s[-n-1] is not s[n]:
            patern = -1
            break
    n += 1
if patern != -1:
    print(patern)
else:
    print(patern)

Submission status: Time Limit Exceeded

Solution code:
import copy
s = list(input())
check = copy.deepcopy(s)

for i in range(s.count("x")):
    check.remove("x")

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

ans = 0
i = 0
while i<len(s)//2:
    if s[i]!=s[-1+(-1)*i]:
        ans += 1
        if s[i]=="x":
            s.insert(len(s)+(-1)*i, ("x"))
        else:
            s.insert(i, ("x"))
    i += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
S = input()
n = 0
s = []
patern = 0
for i in range(len(S)):
    s.append(S[i])
while n < len(s):
    if s[n] is 'x':
        if s[-n-1] is not 'x':
            s.append('x')
            patern += 1
    else:
        if s[-n-1] is 'x':
            s.insert(n,'x')
            patern += 1
        elif s[-n-1] is not s[n]:
            patern = -1
            break
    n += 1
if patern != -1:
    print(patern)
else:
    print(patern)

Submission status: Time Limit Exceeded

Solution code:

s=list(input())


l=0
r=len(s)-1

count=0
while True:
    #print(s,l,r)
    if s[l]!=s[r]:
        if s[l]=="x":
            #s.insert(r+1,"x")
            l+=1
        elif s[r]=="x":
            s.insert(l,"x")
            #r-=1
            l+=1
        else:
            res=-1
            break

        #print(s,l,r)


        count+=1
    else:
        r-=1
        l+=1

    if l>=r:
        res=count
        break


print(res)

Submission status: Time Limit Exceeded

Solution code:
s=list(input())


l=0
r=len(s)-1

count=0
while True:
    #print(s,l,r)
    if s[l]!=s[r]:
        if s[l]=="x":
            s.insert(r+1,"x")
            l+=1
        elif s[r]=="x":
            s.insert(l,"x")
            #r-=1
            l+=1
        else:
            res=-1
            break

        #print(s,l,r)


        count+=1
    else:
        r-=1
        l+=1

    if l>=r:
        res=count
        break


print(res)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
S = input()
N = len(S)
i = 0
j = N-1
ans = 0
while i < j:
    if S[i] == 'x' and S[j] != 'x':
        ans += 1
        i += 1
    elif S[i] != 'x' and S[j] == 'x':
        ans += 1
        j -= 1
    elif S[i] == S[j]:
        i += 1
        j -= 1
    else:
        ans = -1
        break
print(ans)

Submission status: Accepted

Solution code:
import sys 
S = input()
A = []
for i,s in enumerate(S):
    if s != 'x':  A.append(i)
if not A:
    print(0)
    sys.exit()
for i in range(len(A)//2):
    if S[A[i]] != S[A[-i-1]]:
        print(-1)
        sys.exit()
ans = abs((len(S)-1-A[-1])-A[0])
for i in range(len(A)//2):
    cnt = abs(A[i+1]-A[i] - (A[-1-i]-A[-2-i]))
    ans += cnt
print(ans)

Submission status: Accepted

Solution code:

def resolve():
    S = input()
    l, r = 0, len(S) - 1
    ans = 0
    while l < r:
        # 次に進める
        if S[l] == S[r]:
            l += 1
            r -= 1
        # r位置にxを追加
        elif S[l] == "x":
            ans += 1
            l += 1
        # l位置にxを追加
        elif S[r] == "x":
            ans += 1
            r -= 1
        else:
            print(-1)
            return

    print(ans)


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import collections as cl
import sys


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 main():
    s = input()

    l, r = 0, len(s) - 1
    x_l, x_r = 0, 0

    while l <= r:
        if s[l] == s[r]:
            l += 1
            r -= 1
            continue
        if s[l] == 'x':
            l += 1
            x_l += 1
            continue
        if s[r] == 'x':
            r -= 1
            x_r += 1
            continue
        print(-1)
        return

    print(x_l + x_r)


main()

Submission status: Accepted

Solution code:
import sys
s = list(input())
if list(set(s)) == ["x"]:
    print(0)
    sys.exit()
t = [i for i in s if i != "x"]
n = len(t)
if "".join(t) != "".join(t[::-1]):
    print(-1)
else:
    dic = {}
    cnt = 0
    if n % 2 == 0:
        for j in range(len(s)):
            if s[j] != "x":
                cnt += 1
                if cnt == n//2:
                    a = s[:j+1]
                    a = a[::-1]
                if cnt == n//2 + 1:
                    b = s[j:]
                    break
        c = 0
        fa = []
        fb = []
        for k in range(len(a)):
            if a[k] == "x":
                c += 1
            else:
                fa.append(c)
                c = 0
        fa.append(c)
        c = 0
        for p in range(len(b)):
            if b[p] == "x":
                c += 1
            else:
                fb.append(c)
                c = 0
        fb.append(c)
        ans = 0
        for q in range(len(fa)):
            ans += max(fa[q],fb[q]) - min(fa[q],fb[q])
        print(ans)
    else:
        for j in range(len(s)):
            if s[j] != "x":
                cnt += 1
                if cnt == int(n/2) + 1:
                    a = s[:j+1]
                    a = a[::-1]
                    b = s[j:]
                    break
        c = 0
        fa = []
        fb = []
        for k in range(len(a)):
            if a[k] == "x":
                c += 1
            else:
                fa.append(c)
                c = 0
        fa.append(c)
        c = 0
        for p in range(len(b)):
            if b[p] == "x":
                c += 1
            else:
                fb.append(c)
                c = 0
        fb.append(c)
        ans = 0
        for q in range(len(fa)):
            ans += max(fa[q],fb[q]) - min(fa[q],fb[q])
        print(ans)

Submission status: Accepted

Solution code:
s = input()
t = ''
for c in s:
    if c != 'x':
        t += c
if t[::-1] != t:
    print(-1)
    exit()
m = len(t)
l = [0] * (m + 1)
ind = 0
for c in s:
    if c == 'x':
        l[ind] += 1
    else:
        ind += 1
ans = 0
for i in range((m+1)//2):
    ans += abs(l[i] - l[-1-i])
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import bisect,collections,copy,itertools,math,string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
def main():
    
    s = S()

    ex = s.replace("x", "")

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

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

    while True:
        l += 1
        r -= 1
        lcnt = 0
        rcnt = 0

        while l < len(s):
            if s[l] == "x":
                lcnt += 1
                l += 1
            else:
                break

        while r > -1:
            if s[r] == "x":
                rcnt += 1
                r -= 1
            else:
                break

        if l > r:
            break
        ans += abs(lcnt-rcnt)

    print(ans)
    
main()

Submission status: Accepted

Solution code:
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from math import gcd
from itertools import combinations,permutations,accumulate, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
import math
import bisect
import heapq
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
#
# インデックス系
# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);
# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);
#
#
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
#mod = 998244353
INF = float('inf')
from sys import stdin
readline = stdin.readline
def readInts():
  return list(map(int,readline().split()))
def readTuples():
    return tuple(map(int,readline().split()))
def I():
    return int(readline())
S = input()
ln = len(S)-1
i = 0
j = ln
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:
        print(-1)
        exit()
print(ans)

Submission status: Accepted

Solution code:
s = input()
cnt = 0

while True:
  if len(s) < 2:
    break
  if s[0] == s[-1]:
    s = s[1:-1]
  elif s[0] == 'x':
    s += 'x'
    cnt += 1
  elif s[-1] == 'x':
    s = 'x' + s
    cnt += 1
  else:
    print (-1)
    exit()
print (cnt)

Submission status: Accepted

Solution code:
from collections import deque
S=input()
deque_S=deque(S)
flag=0
ans=0
while True:
    if len(deque_S)<=1:
        break
    if deque_S[0] == deque_S[-1]:
        deque_S.pop()
        deque_S.popleft()
    else:
        if deque_S[0] == 'x':
            ans+=1
            deque_S.popleft()
        elif deque_S[-1] == 'x':
            ans+=1
            deque_S.pop()
        else:
            flag=1
            break
if flag==1:
    print(-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
from collections import deque

s = deque(list(input()))

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

print(ans)

Submission status: Accepted

Solution code:
s = input()
l = 0
r = len(s)-1

flag = True
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:
    flag = False
    break

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

Submission status: Accepted

Solution code:
S = input()
i = 0
j = len(S) - 1
cnt = 0

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

Submission status: Accepted

Solution code:
import sys
from sys import exit
from collections import deque
from bisect import bisect_left, bisect_right, insort_left, insort_right
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import gcd, sin, cos, tan, asin, acos, atan, degrees, radians

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x,d=1):
        self.setdefault(x,0)
        self[x] += d
    def list(self):
        l = []
        for k in self:
            l.extend([k]*self[k])
        return l
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]
def pf(x):
    C = counter()
    p = 2
    while x>1:
        k = 0
        while x%p==0:
            x //= p
            k += 1
        if k>0:
            C.add(p,k)
        p = p+2-(p==2) if p*p<x else x
    return C

s=input()
N=len(s)
t=''.join(list(s.replace('x',''))[::-1])
if s.replace('x','')!=t:
    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':
        ans+=1
        i+=1
    else:
        ans+=1
        j-=1
print(ans)

Submission status: Accepted

Solution code:
import sys
# sys.setrecursionlimit(100000)
from collections import deque


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


def input_int():
    return int(input())


def input_int_list():
    return [int(i) for i in input().split()]


def main():
    S_deq = deque(list(input()))
    cnt = 0
    while S_deq:
        # 残り1文字のとき
        if len(S_deq) == 1:
            S_deq.pop()
        # 両端が同じ文字のとき
        elif S_deq[0] == S_deq[-1]:
            S_deq.popleft()
            S_deq.pop()
        # 片方が x のとき
        elif S_deq[0] == "x":
            S_deq.popleft()
            cnt += 1
        elif S_deq[-1] == "x":
            S_deq.pop()
            cnt += 1
        else:
            print(-1)
            return
    print(cnt)
    return


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    #input data
    import sys
    input = lambda:sys.stdin.readline().strip()
    S = input()
    N = len(S)
    #solve
    left = 0
    right = N-1

    ans = 0
    while left<=right:
        if right==left:
            break
        if S[left]==S[right]:
            left+=1
            right-=1
            continue
        if S[left]!='x' and S[right]!='x':
            print(-1);exit()
        if S[left]=='x':
            left+=1
            ans+=1
        if S[right]=='x':
            right-=1
            ans+=1
    if right>left:
        print(-1)
    else:
        print(ans)


if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
s = input()

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

while l < r:
    lx = 0
    while s[l] == "x" and l < len(s)-1:
        lx += 1
        l += 1

    rx = 0
    while s[r] == "x" and r > 0:
        rx += 1
        r -= 1

    if s[l] == s[r]:
        cnt += abs(rx-lx)

        l += 1
        r -= 1
    else:
        cnt = -1
        break

print(cnt)

Submission status: Accepted

Solution code:
from collections import deque

S = deque(list(input()))

ans = 0
while len(S) > 1:
    l = S.popleft()
    r = S.pop()
    if l == r:
        continue
    elif l == 'x':
        ans += 1
        S.append(r)
    elif r == 'x':
        ans += 1
        S.appendleft(l)
    else:
        print(-1)
        exit()
print(ans)

Submission status: Accepted

Solution code:
import numpy as np

S = np.array(list(input()))
num_x = np.count_nonzero(S == 'x')
# print(f'{num_x=}')
A = [s for s in S if s != 'x']
# print(f'{S=}, {A=}')

if len(A) % 2 == 0:
    L = A[:len(A) // 2]
    R = A[len(A) // 2:][::-1]
else:
    L = A[:len(A) // 2]
    R = A[len(A) // 2 + 1:][::-1]
# print(f'{L=}, {R=}')
if not np.all(L == R):
    print(-1)
    exit()

# x以外の文字でsplitをする？'x' '' 'x' ''

T = []
subset = ''
for s in S:
    # print(f'{subset=}')
    if s == 'x':
        subset += 'x'
    else:
        T.append(subset)
        subset = ''
T.append(subset)
len_T = np.array([len(t) for t in T])
# print(f'{T=}, {len_T=}, {len_T - len_T[::-1]}')
ans = np.abs(len_T - len_T[::-1]).sum() // 2
print(ans)

Submission status: Accepted

Solution code:
import numpy as np

S = np.array(list(input()))
num_x = np.count_nonzero(S == 'x')
# print(f'{num_x=}')
A = [s for s in S if s != 'x']
# print(f'{S=}, {A=}')

if len(A) % 2 == 0:
    L = A[:len(A) // 2]
    R = A[len(A) // 2:][::-1]
else:
    L = A[:len(A) // 2]
    R = A[len(A) // 2 + 1:][::-1]
# print(f'{L=}, {R=}')
if not np.all(L == R):
    print(-1)
    exit()

# 真ん中までSとreverse_Sを進めていってXの数が足りない分それぞれ足す
# x以外の文字でsplitをする？'x' '' 'x' ''

T = []
subset = ''
for s in S:
    # print(f'{subset=}')
    if s == 'x':
        subset += 'x'
    else:
        T.append(subset)
        subset = ''
T.append(subset)
len_T = np.array([len(t) for t in T])
# print(f'{T=}, {len_T=}, {len_T - len_T[::-1]}')
ans = np.abs(len_T - len_T[::-1]).sum() // 2
print(ans)

Submission status: Accepted

Solution code:
import numpy as np

S = np.array(list(input()))
num_x = np.count_nonzero(S == 'x')
# print(f'{num_x=}')
A = [s for s in S if s != 'x']
# print(f'{S=}, {A=}')

if len(A) % 2 == 0:
    L = A[:len(A) // 2]
    R = A[len(A) // 2:][::-1]
else:
    L = A[:len(A) // 2]
    R = A[len(A) // 2 + 1:][::-1]
# print(f'{L=}, {R=}')
if not np.all(L == R):
    print(-1)
    exit()
# if len(L) == 0 and len(R) == 0:
#     print(0)
#     exit()

reverse_S = S[::-1]
i = 0
j = 0
# 真ん中までSとreverse_Sを進めていってXの数が足りない分それぞれ足す
# x以外の文字でsplitをする？'x' '' 'x' ''

T = []
subset = ''
for s in S:
    # print(f'{subset=}')
    if s == 'x':
        subset += 'x'
    else:
        T.append(subset)
        subset = ''
T.append(subset)
len_T = np.array([len(t) for t in T])
# print(f'{T=}, {len_T=}, {len_T - len_T[::-1]}')
ans = np.abs(len_T - len_T[::-1]).sum() // 2
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()
  l=0
  r=len(s)-1

  ans=0
  while l<r:
    if s[l]=='x':
      if s[r]=='x':
        l+=1
        r-=1
      else:
        l+=1
        ans+=1
    else:
      if s[r]=='x':
        r-=1
        ans+=1
      else:
        if s[l]==s[r]:
          l+=1
          r-=1
        else:
          return -1

  return ans

# main()
print(main())

Submission status: Accepted

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


if __name__ == "__main__":
    main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
'''
Created on 2020/09/02

@author: harurun
'''
def main():
  import sys
  pin=sys.stdin.readline
  pout=sys.stdout.write
  perr=sys.stderr.write
  
  s=list(pin()[:-1])
  
  cnt=0
  while s:
    if len(s)==1:
      break
    elif s[0]==s[-1]:
      s.pop(0)
      s.pop(-1)
    else:
      if s[0]!='x' and s[-1]!='x':
        print(-1)
        return 
      else:
        if s[0]=='x':
          s.pop(0)
        else:
          s.pop(-1)
        cnt+=1
  print(cnt)
  return 
main()

Submission status: Accepted

Solution code:
s = input()

i = 0
j = len(s)-1

ans = 0
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
    else:
        break

if i >= j:
    print(ans)
else:
    print(-1)

Submission status: Accepted

Solution code:
l=a=0;r=len(s:=input())-1
while l<r:
  X=((L:=s[l])==(R:=s[r]))
  l+=((L:=(L=='x'))+X>0)
  r-=((R:=(R=='x'))+X>0)
  a+=(X<1)*(L+R>0)
  if X+L+R<1:a=-1;break
print(a)

Submission status: Accepted

Solution code:
l=a=0;r=len(s:=input())-1;c='x'
while l<r:
  X=((L:=s[l])==(R:=s[r]))
  l+=((L:=(L==c))+X>0)
  r-=((R:=(R==c))+X>0)
  a+=(X<1 and (L+R>0))
  if X+L+R<1:a=-1;break
print(a)

Submission status: Accepted

Solution code:
l=a=0;r=len(s:=input())-1;c='x'
while l<r:
  L,R=s[l],s[r]
  X=(L==R)
  L=(L==c)
  R=(R==c)
  l+=(L+X>0)
  r-=(R+X>0)
  a+=(X<1 and (L+R>0))
  if X+L+R<1:a=-1;break
print(a)

Submission status: Accepted

Solution code:
A=list(input())
from collections import deque
A=deque(A)
cnt=0
while len(A)>1:
   if A[0]==A[-1]:
      A.pop()
      A.popleft()
   elif (A[0]!="x" and A[-1]=="x" ):
      cnt+=1
      A.pop()
   elif (A[0]=="x" and A[-1]!="x" ):
      cnt+=1
      A.popleft()
   else:
      print(-1)
      exit()
print(cnt)

Submission status: Accepted

Solution code:
#import sys
#import numpy as np
import math
#from fractions import Fraction
import itertools
from collections import deque
from collections import Counter
import heapq
from fractions  import gcd
#input=sys.stdin.readline
#import bisect
s=input()
n=len(s)
t=[]
x="x"
for i in range(n):
    if s[i]!=x:
        t.append([s[i],i])
m=len(t)
resl=0
resr=n-1
ans=0
for i in range((m+1)//2):
    lt,l=t[i]
    rt,r=t[m-1-i]
    if lt==rt:
        ans+=abs((l-resl)-(resr-r))
        resl=l
        resr=r
    else:
        print(-1)
        exit()
print(ans)

Submission status: Accepted

Solution code:
import sys
s = input()
num = len(s)
l, r = 0, num-1
ans = 0

while l < r:
    if s[l] == s[r]:
        l += 1
        r -= 1
    else:
        ans += 1
        if s[l] == 'x':
            l += 1
        elif s[r] == 'x':
            r -= 1
        else:
            print(-1)
            sys.exit()
print(ans)