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:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from math import factorial, sqrt, ceil, gcd
from functools import lru_cache, reduce
from decimal import Decimal
from operator import mul

INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)


# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# 組合せnCr
def combinations_count(n, r):
    if n < r:
        return 0
    r = min(r, n - r)
    numer = reduce(mul, range(n, n - r, -1), 1)
    denom = reduce(mul, range(1, r + 1), 1)
    return numer // denom

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定
def is_prime(n):
    if n <= 1:
        return False
    p = 2
    while True:
        if p ** 2 > n:
            break
        if n % p == 0:
            return False
        p += 1
    return True


# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret

def make_divisors(n):
    lower_divisors , upper_divisors = [], []
    i = 1
    while i*i <= n:
        if n % i == 0:
            lower_divisors.append(i)
            if i != n // i:
                upper_divisors.append(n//i)
        i += 1
    return lower_divisors + upper_divisors[::-1]

# ここから書き始める
s = input()
n = len(s)

def func(s, n):
    if "x" not in s:
        if s == s[::-1]:
            # print(0)
            return 0
        else:
            # print(-1)
            return -1
    else:
        s3 = s.replace("x", "")
        if s3 != s3[::-1]:
            return -1
        ans = 0
        s2 = s
        i = 0
        while True:
            m = len(s2)
            if i >= m:
                break
            if s2[i] == "x" and s2[m - i - 1] != "x":
                s2 = s2[:i] + s2[i + 1:]
                ans += 1
            elif s2[i] != "x" and s2[m - i - 1] == "x":
                s2 = s2[:m - i - 1] + s2[m - i:]
                ans += 1
            else:
                i += 1
        # print(ans)       
        return ans

        # ans1 = 0
        # cnt1 = 0
        # for i in range(n):
        #     if s[i] == "x":
        #         if s[n - i - 1 + cnt1] != "x":
        #             ans1 += 1

        # ans2 = 0
        # for i in reversed(range(n)):
        #     print("n - i - 1 - ans2 =", n - i - 1 - ans2)
        #     if s[i] == "x":
        #         if s[n - i - 1 - ans2] != "x":
        #             ans2 += 1
        # print("ans1 =", ans1)
        # print("ans2 =", ans2)

ans = func(s, n)
print(ans)

# def dfs(i, n, ret):
#     if i == n:
#         print("%s : %d" % (ret, func(ret, n)))
#         # print(ret)
#         # print(func(ret, n))
#         return 
    
#     dfs(i + 1, n, ret + "a")
#     dfs(i + 1, n, ret + "b")
#     dfs(i + 1, n, ret + "x")

# n = 3
# dfs(0, n, "")

Submission status: Accepted

Solution code:
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def i(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def L(): return list(map(int,input().split()))
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10 ** 9)
INF = 10**9
mod = 10**9+7

S = deque(list(s()))
cnt = 0
N = len(S)
for i in range(N):
    N = len(S)
    if N <= 1:
        break
    if S[0] == 'x':
        if S[N-1] == 'x':
            S.pop()
            S.popleft()
        else:
            cnt += 1
            S.popleft()
    else:
        a = S[0]
        if S[N-1] == 'x':
            cnt += 1
            S.pop()
        elif S[N-1] == a:
            S.pop()
            S.popleft()
        else:
            print(-1)
            exit()
print(cnt)

Submission status: Accepted

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

Submission status: Accepted

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

ans = 0
while s:
    top = s[0]
    end = s[-1]
    if top != end:
        if not (top == "x" or end == "x"):
            print(-1)
            break
        else:
            if top == "x":
                s.popleft()
            else:
                s.pop()
            ans += 1
    else:
        s.popleft()
        if s:
            s.pop()
else:
    print(ans)

Submission status: Accepted

Solution code:
S = list(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':
        l += 1
        ans += 1
    elif S[r] == 'x':
        r -= 1
        ans += 1
    else:
        print (-1)
        exit()

print (ans)

Submission status: Accepted

Solution code:
s = input()
s2 = []
for i in range(len(s)):
    if s[i] != 'x':
        s2.append(s[i])
if s2 != s2[::-1]:
    print(-1)
    exit()
lis = []
j = 0
cnt = 0
for i in range(len(s)):
    if s[i] == 'x':
        cnt += 1
    else:
        lis.append(cnt)
        cnt = 0

lis.append(cnt)
ans = 0
for i in range(len(lis)//2):
    ans += abs(lis[i]-lis[-(i+1)])
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline().rstrip
#input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np


def main():
	s=input()
	#print(s)

	n=len(s)

	l=0
	r=n-1

	ans=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":
			ans+=1
			r-=1

		else:
			print(-1)
			exit()

	print(ans)
	return

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:

import sys
input = sys.stdin.readline
#input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np


def main():
	s=input().rstrip()

	n=len(s)

	l=0
	r=n-1

	ans=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":
			ans+=1
			r-=1

		else:
			print(-1)
			exit()

	print(ans)
	return

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:

import sys
read = sys.stdin.buffer.read
#input = sys.stdin.readline
#input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np


def main():
	s=input()

	n=len(s)

	l=0
	r=n-1

	ans=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":
			ans+=1
			r-=1

		else:
			print(-1)
			exit()

	print(ans)
	return

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
"""
import sys
read = sys.stdin.buffer.read
input = sys.stdin.readline
#input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np
"""

def main():
	s=input()

	n=len(s)

	l=0
	r=n-1

	ans=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":
			ans+=1
			r-=1

		else:
			print(-1)
			exit()

	print(ans)
	return

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
def main():
    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":
            l += 1
            ans += 1
        elif s[r] == "x":
            r -= 1
            ans += 1
        else:
            print(-1)
            exit()
    print(ans)
    return

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    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":
            l += 1
            ans += 1
        elif s[r] == "x":
            r -= 1
            ans += 1
        else:
            print(-1)
            exit()
    print(ans)
    return

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right


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




if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def is_valid():
    x_removed_S = S.replace("x", "")
    M = len(x_removed_S)
    for i in range(M // 2):
        if x_removed_S[i] != x_removed_S[M - i - 1]:
            return False
    return True


S = input()
N = len(S)
if is_valid():
    ans = 0
    left, right = 0, N - 1
    while left < right:
        if S[left] == S[right]:
            left += 1
            right -= 1
            continue
        elif S[left] == "x":
            ans += 1
            left += 1
        else:
            ans += 1
            right -= 1
    print(ans)
else:
    print(-1)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache


#############
# Constants #
#############

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

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)


#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  divisors.sort()
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
S = S()
N = len(S)
l = 0
r = N-1

count = 0
while l<r:
  if S[l] != S[r]:
    if S[l] == "x":
      count += 1
      l += 1
    elif S[r] == "x":
      count += 1
      r -= 1
    else:
      print(-1)
      exit()
  else:
    l += 1
    r -= 1
print(count)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
#from decimal import *

S = deque(input())

ans = 0
while S:
	if len(S) == 1:
		S.pop()
	elif S[0] == S[-1]:
		S.pop()
		S.popleft()
	else:
		if S[0] == "x":
			S.append("x")
			ans += 1
		elif S[-1] == "x":
			S.appendleft("x")
			ans += 1
		else:
			print(-1)
			break
else:
	print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
#from decimal import *

s = input()
N = len(s)

t = ""
for X in s:
	if X != "x":
		t += X

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

s2 = s[::-1]

i = 0
j = 0
ans = 0

while i < N and j < N:
	if s[i] == s2[j]:
		i += 1
		j += 1
	else:
		if s[i] == "x":
			i += 1
		else:
			j += 1
		ans += 1

ans += (N - i)*(i < N) + (N - j)*(j < N)

print(ans//2)

Submission status: Accepted

Solution code:
import sys
s = input()
a, b = '', ''
for i in range(len(s)):
    if s[i] != 'x':
        a += s[i]
        b = s[i] + b
if a != b:
    print(-1)
    sys.exit()
ans = 0
while len(s) != 0:
    if s[0] == s[-1]:
        s = s[1:-1]
    elif s[0] == 'x' and s[-1] == 'x':
        if len(s) == 1:
            s = ''
        else:
            s = s[1:-1]
    elif s[0] == 'x':
        s = s[1:]
        ans += 1
    elif s[-1] == 'x':
        s = s[:-1]
        ans += 1
print(ans)

Submission status: Accepted

Solution code:
s = list(map(str,input()))
l = len(s)
cntf = 0
cntl = l-1
ans = 0

while cntf < cntl:
    if s[cntf] == s[cntl]:
        cntf += 1
        cntl -= 1
    else:
        if s[cntf] == "x":
            ans += 1
            cntf += 1
        elif s[cntl] == "x":
            ans += 1
            cntl -= 1
        else:
            print(-1)
            exit()

print(ans)

Submission status: Accepted

Solution code:
s = input()

l = 0
r = len(s)-1

rlt = 0

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

Submission status: Accepted

Solution code:
from collections import deque
s = deque(input())
cou = 0
while len(s)!=0:
  a = s[0]
  b = s[-1]
  if a=='x' and b!='x':
    cou += 1
    s.popleft()
  elif a!="x" and b=='x':
    cou += 1
    s.pop()
  elif a=="x" and b=='x':
    if len(s)==1:
      s.popleft()
    else:   
      s.popleft()
      s.pop()
  elif a==b:
    if len(s)==1:
      s.popleft()
    else:   
      s.popleft()
      s.pop()
  else:
    print(-1)
    exit()
print(cou)

Submission status: Accepted

Solution code:
s = input()

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

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

print(ans)

Submission status: Accepted

Solution code:
from collections import deque
S = deque(input())

ans = 0
while len(S):
    if S[0] == S[-1]:
        if len(S) > 1:
            S.popleft()
            S.pop()
        else:
            S.pop()
    else:
        if S[0] != "x" and S[-1] != "x":
            print(-1)
            exit()
        elif S[0] != "x":
            S.pop()
            ans += 1
        elif S[-1] != "x":
            S.popleft()
            ans += 1
print(ans)

Submission status: Accepted

Solution code:
import sys

S = sys.stdin.readline().rstrip()
not_x = []

for i, s in enumerate(S):
    if s != "x":
        not_x.append(s)

not_x_nums = len(not_x)
mid = not_x_nums // 2

if not_x_nums % 2 == 1:
    left = not_x[:mid]
    right = not_x[mid + 1:][::-1]
else:
    left = not_x[:mid]
    right = not_x[mid:][::-1]

if left == right:
    ans = 0
    left = []
    right = []
    tmp = 0
    cnt = 0
    if not_x_nums % 2 == 1:
        mid += 1
    for s in S:
        if s != "x":
            left.append(tmp)
            tmp = 0
            cnt += 1
        else:
            tmp += 1
        if cnt == mid:
            break
    tmp = 0
    cnt = 0
    for s in S[::-1]:
        if s != "x":
            right.append(tmp)
            tmp = 0
            cnt += 1
        else:
            tmp += 1
        if cnt == mid:
            break
    for l, r in zip(left, right):
        ans += abs(l - r)
    print(ans)
else:
    print(-1)

Submission status: Accepted

Solution code:
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def S(): return input()


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


def MS(): return map(str, input().split())


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


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


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


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


YNL = {False: 'No', True: 'Yes'}
YNU = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**19
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

show_flg = False
# show_flg = True


def main():
    s = S()
    d = deque(s)
    ans = 0

    while len(d) > 1:
        l = d.popleft()
        r = d.pop()

        if l == r:
            continue
        elif l == 'x':
            ans += 1
            d.append(r)
        elif r == 'x':
            ans += 1
            d.appendleft(l)
        else:
            print(-1)
            return

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from collections import deque

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


def solve():
    s = rl().rstrip()
    
    que = deque(s)
    ans = 0
    while 1 < len(que):
        if que[0] == que[-1]:
            que.pop()
            que.popleft()
        elif que[0] == 'x':
            que.append('x')
            ans += 1
        elif que[-1] == 'x':
            que.appendleft('x')
            ans += 1
        else:
            print(-1)
            return
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(tin())
mod=1000000007

#+++++

def main():
	#a = int(input())
	#b , c = tin()
	s = list(input())
	cc=[c for c in s if c != 'x']
	ccc=cc[::-1]
	if cc != ccc:
		return -1
	add=0
	ci=0
	ls = len(s)
	for i, c in enumerate(s):
		#cc = s[ls-1-ci]
		#if cc == c:
		#	ci+=1
		#else:
		while c != s[ls-1-ci]:
			pa((i,ci,c,s[ls-1-ci]))
			if c == 'x':
				add+=1
				ci-=1
				break
			else:
				add+=1
				ci+=1
		ci+=1
		if i + ci >= ls:
			break
	return add
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Accepted

Solution code:
s = input()
LS = len(s)
rs = s[::-1]
lc = []
rc = []
lx = 0
rx = 0
for i in range(LS):
    if s[i] != 'x':
        lc.append(s[i])
    if rs[i] != 'x':
        rc.append(rs[i])
cnt = 0
if lc==rc or len(lc)+len(rc)==1:
    i = 0
    j = LS-1
    while j>i:
        if s[i]!=s[j]:
            if s[i]=='x':
                cnt+=1
                i +=1
            elif s[j]=='x':
                cnt+=1
                j -=1
        else:
            i +=1
            j -=1
    print(cnt)
else:
    print(-1)

Submission status: Accepted

Solution code:
s= input()
ans = 0
l = 0
r = 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:
s=input()

cnt=0
while len(s)>1:
    if s[0]==s[-1]:
        s= s[1:-1]
    elif s[0]=="x" and s[-1]!="x":
        s = s[1:]
        cnt +=1
    elif s[-1]=="x" and s[0]!="x":
        s = s[:-1]
        cnt +=1
    else:
        cnt=-1
        break
print(cnt)

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline

# 両端から見ていき、回文になっていないときに片方がxだったら、ans += 1してxのほうのインデックスを1進める
# 両方ともxでなかったら-1を出力

S = readline().rstrip()

left = 0
right = len(S) - 1
ans = 0
while left < right:
  if S[left] == S[right]:
    left += 1
    right -= 1
  else:
    if S[left] == "x":
      ans += 1
      left += 1
    elif S[right] == "x":
      ans += 1
      right -= 1
    else:
      print(-1)
      break
else:
  print(ans)

Submission status: Accepted

Solution code:
s = str(input())
ns = s.replace('x', '')
l = len(ns)
if l == 0:
    print(0)
elif l == 1:
    idx = s.find(ns)
    print(abs(idx - (len(s) - idx - 1)))
else:
    cnt = 0
    L = []
    for i in range(l // 2):
        if ns[i] != ns[-(i+1)]:
            print(-1)
            break
        else:
            L.append(ns[i])
    else:
        if l % 2:
            L.append(ns[i+1])
        pleft = 0
        pright = 0
        for c in L:
            if pleft == 0:
                left = s.find(c)
            else:
                left = s[pleft:].find(c)
            if pright == 0:
                right = len(s) - s.rfind(c) - 1
            else:
                right = len(s) - (s[:-pright].rfind(c) + pright + 1)
            pleft = left + pleft + 1
            pright = right + pright + 1
            cnt += abs(left - right)
        print(cnt)

Submission status: Accepted

Solution code:
s=input()
from collections import deque
s=deque(s)
ans=0
while len((s)):
  if s[0]==s[-1]:
    if len((s))==1:
      s.pop()
      break
    else:
      s.pop()
      s.popleft()
  else:
    if s[0]=="x" and s[-1]!="x":
      s.append("x")
      ans+=1
    elif s[0]!="x" and s[-1]=="x":
      s.appendleft("x")
      ans+=1
    elif s[0]!="x" and s[-1]!="x":
      print(-1)
      exit(0)

print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque

s = deque(map(str, input().rstrip()))

cnt = 0
while s:
    if s[0] != s[-1]:
        if s[0] != "x" and s[-1] != "x":
            print(-1)
            sys.exit()
        elif s[0] == "x":
            tmp = s.popleft()
        else:
            tmp = s.pop()
        cnt += 1
    elif len(s) <= 1:
        break
    else:
        s.popleft()
        s.pop()

print(cnt)