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
stdin = sys.stdin

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from collections import deque

s = deque(lc())
lens = len(s)

ok = True
ans = 0

while len(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:
            ok = False
            break
    
if ok:
    print(ans)
else:
    print(-1)

Submission status: Accepted

Solution code:
import re
s = input()
pa = s.replace('x', '')
if pa != pa[::-1]:
    print(-1)
else:
    ans = 0
    sp = re.split(r'[a-wyz]', s)
    for r, l in zip(sp, sp[::-1]):
        ans += abs(len(r) - len(l))
    print(ans // 2)

Submission status: Accepted

Solution code:
import copy
S = list(input())
s = copy.copy(S)
ans = 1
i = 0
while True:
    if i >= len(s):
        break
    if s[i] == "x":
        del s[i]
        i -= 1
    i += 1

def main(s):
    for i in range(int((len(s)) / 2)):
        if s[i] != s[len(s) - 1 - i]:
            print(-1)
            return 0
    cnt = 0
    num = [-1]
    for i in range(len(S)):
        if S[i] != "x":
            num.append(i)
    num.append(len(S))
    i = 0
    s = copy.copy(S)
    cnt = 0
    #print(num)
    if len(num) % 2 == 0:
        i = int(len(num) / 2)
        for j in range(i, len(num) - 1):
            #print(i, j, j + 1, len(num) - j - 1, len(num) - j - 2)
            cnt += abs(abs(num[j] - num[j + 1]) - abs(num[len(num) - j - 1] - num[len(num) - j - 2]))
            #print(abs(num[j] - num[j + 1]), i, j)
            #print(abs(num[len(num) - j - 1] - num[len(num) - j - 2]))
    else:
        i = int(len(num) / 2)
        for j in range(i, len(num) - 1):
            #print(i, j, j + 1, len(num) - j - 1, len(num) - j - 2)
            cnt += abs(abs(num[j] - num[j + 1]) - abs(num[len(num) - j - 1] - num[len(num) - j - 2]))
            #print(abs(num[j] - num[j + 1]), i, j)
            #print(abs(num[len(num) - j - 1] - num[len(num) - j - 2]))
    print(cnt)
    return 0
        
            
main(s)

Submission status: Accepted

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

while l<r:
  if s[l]==s[r]:
    l+=1
    r-=1
  elif s[l]=="x":
    l+=1
    c+=1
  elif s[r]=="x":
    r-=1
    c+=1
  else:
    print(-1)
    break
else:
  print(c)

Submission status: Accepted

Solution code:
s = raw_input()

l = 0
r = len(s)-1

ans = 0
while l <= r and -1 < l < len(s) and -1 < r < len(s):
	if s[l] == s[r]:
		l += 1
		r -= 1

	else :
		if s[l] == "x":
			l += 1
			ans += 1
		elif s[r] == "x":
			r -= 1
			ans += 1

		else :
			print -1
			quit()
	
print ans

Submission status: Accepted

Solution code:
s = input()
go = []
back = []
start = 0
end = len(s)-1
res = 0
while start<=end:
    gox = 0
    backx = 0
    while s[end] == 'x' or s[start] == 'x':
        if s[start] == 'x' and start<end:
            start+=1
            gox += 1
        if s[end] == 'x'and start<end:
            end -= 1
            backx +=1
        if start == end:break
    if start == end and s[start] == 'x':
        break
    if s[start] == s[end]:
        start += 1
        end -=1
        res += abs(gox-backx)
        gox = 0
        backx = 0
    else:
        res = -1
        break

print(res)

Submission status: Accepted

Solution code:
def main():
    s = input()

    ss = [i for i in s if i != 'x']
    for i in range(len(ss)//2):
        if ss[i] != ss[len(ss)-1-i]:
            print("-1")
            return

    x_idx, idx, j = [0 for i in range(len(ss)+1)], 0, 0
    while idx < len(s):
        cnt = 0
        while idx < len(s) and s[idx] == 'x':
            cnt += 1
            idx += 1
        x_idx[j] = cnt

        while idx < len(s) and s[idx] != 'x':
            idx += 1
            j += 1

    ans = 0
    for i in range(len(ss)+1):
        if x_idx[i] != x_idx[len(ss)-i]:
            ans += max(x_idx[len(ss)-i], x_idx[i]) - min(x_idx[len(ss)-i], x_idx[i])
            x_idx[i] = x_idx[len(ss)-i] = max(x_idx[len(ss)-i], x_idx[i])

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

from collections import defaultdict
import sys,heapq,bisect,math,itertools,string,queue,datetime
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inpl(): return list(map(int, input().split()))
def inpl_s(): return list(input().split())

S = input()
Sx = S.replace('x','')

if Sx == Sx[::-1]:
	xx = []
	tmp = 0
	for s in S:
		if s == 'x':
			tmp += 1
		else:
			xx.append(tmp)
			tmp = 0
	xx.append(tmp)
	ans = 0
	L = len(xx)
	for i in range(L//2):
		ans += abs(xx[i]-xx[L-1-i])
	print(ans)
else:
	print(-1)

Submission status: Accepted

Solution code:
S = input()
S2 = "".join([s for s in S if s != "x"])

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

A = []
cnt = 0
for s in S:
    if s != "x":
        A.append(cnt)
        cnt = 0
    else:
        cnt += 1
A.append(cnt)

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
s=input()
ss=""
res=0
for c in s:
    ss+=c if c!="x" else ""
if ss!=ss[-1::-1]:
    print(-1)
elif len(ss)%2==0:
    ss=ss[:len(ss)//2]
    for c in ss:
        l=s.find(c)
        r=s.rfind(c)
        res+=max(l,len(s)-1-r)-min(l,len(s)-1-r)
        s=s[l+1:r]
    print(res)
else:
    cent=ss[len(ss)//2]
    ss=ss[:len(ss)//2]
    for c in ss:
        l=s.find(c)
        r=s.rfind(c)
        res+=max(l,len(s)-1-r)-min(l,len(s)-1-r)
        s=s[l+1:r]
    l=s.find(cent)
    r=s.rfind(cent)
    res+=max(l,len(s)-1-r)-min(l,len(s)-1-r)
    print(res)

Submission status: Accepted

Solution code:
from collections import deque
s = input()
tmp = s.replace('x','')
if tmp == tmp[::-1]:
  left = 0
  right = len(s)-1
  result = deque()
  while 1:
    if right == left:
      result.append(s[left])
      break
    if s[left] == s[right]:
      result.appendleft(s[left])
      result.append(s[right])
      left += 1
      right -= 1
    else:
      result.appendleft('x')
      result.append('x')
      if s[left] == 'x':
        left += 1
      else:
        right -= 1
    if right < left:
      break
  print(len(result)-len(s))
else:
  print(-1)

Submission status: Accepted

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

s = input()

swox = "".join(list(filter("x".__ne__, list(s))))

# print(s, swox)
def is_palind(a):
    for i in range(len(a)//2):
        if a[i] != a[-i-1]:
            return False
    return True

if not is_palind(swox):
    print(-1)
    sys.exit(0)
#
l = 0
r = -1
count = 0
# print(s)
while True:
    # print(l, r+len(s))
    # print(s[l],s[r])
    if l >= r+len(s):
        break
    if s[l] == "x" and s[r] == "x":
        l += 1
        r -= 1
    elif s[l] == "x":
        l += 1
        count += 1
    elif s[r] == "x":
        r -= 1
        count += 1
    else:
        l += 1
        r -= 1
print(count)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
s = input()

s_x = s.replace('x', '')
s = list(s)

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

Submission status: Accepted

Solution code:
import sys
S=raw_input()

cnt=0
while len(S)>1:
	#print S,cnt
	if S[0]==S[-1]:
		S=S[1:-1]
	elif S[0]!=S[-1] and S[0]=="x":
		cnt+=1
		S=S+"x"
	elif S[0]!=S[-1] and S[-1]=="x":
		S="x"+S
		cnt+=1
	else:
		print "-1"
		sys.exit()
print cnt

Submission status: Accepted

Solution code:
def main():
    s = list(input())
    wox = [i for i in s if i != "x"]
    if len(wox) == 0: return 0
    wowr = list(reversed(wox))
    for i in range(len(wox)//2+1):
        if wox[i] != wowr[i]:
            return -1
    sr = list(reversed(s))
    si = ri = 0
    ret = 0
    while si < len(s) and ri < len(sr):
        if s[si] == sr[ri]:
            si += 1
            ri += 1
        elif s[si] == "x":
            si += 1
            ret += 1
        else:
            ri += 1
            ret += 1
    return (ret + len(s) - min(si,ri))//2
print(main())

Submission status: Accepted

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

# CODE FESTIVAL 2017 qual C
# C - Inserting 'x'
# http://code-festival-2017-qualc.contest.atcoder.jp/tasks/code_festival_2017_qualc_c

def f(str):
    numOfX = 0
    numOfXs = []
    letters = []
    
    for c in str:
        if c == 'x':
            numOfX += 1
        else:
            letters.append(c)
            numOfXs.append(numOfX)
            numOfX = 0
            
    numOfXs.append(numOfX)

    if any(letters[i] != letters[-i-1] 
           for i in range(len(letters)//2)):
        return -1

    return sum(abs(numOfXs[i] - numOfXs[-i-1]) 
            for i in range(len(numOfXs)//2))

def test():
    assert f('xabxa') == 2
    assert f('ab') == -1
    assert f('a') == 0
    assert f('oxxx') == 3


def main():
    str = input()
    print(f(str))

if __name__ == '__main__':
    main()

Submission status: Accepted

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

def f(str):
    numOfX = 0
    numOfXs = []
    letters = []
    
    for c in str:
        if c == 'x':
            numOfX += 1
        else:
            letters.append(c)
            numOfXs.append(numOfX)
            numOfX = 0
            
    numOfXs.append(numOfX)

    for i in range(len(letters)//2):
        if letters[i] != letters[-i-1]:
            return -1

    a = 0
    for i in range(len(numOfXs)//2):
        a += abs(numOfXs[i] - numOfXs[-i-1])
            
    return a

def test():
    assert f('xabxa') == 2
    assert f('ab') == -1
    assert f('a') == 0
    assert f('oxxx') == 3


def main():
    str = input()
    print(f(str))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s = input()

count = 0
left, right = 0, len(s)-1
while True:
    if s[left] == s[right]:
        left, right = left+1, right-1
    elif s[left] == 'x':
        left = left+1
        count += 1
    elif s[right] == 'x':
        right = right-1
        count += 1
    else :
        count = -1
        break
    if left >= right:
        break
print(count)

Submission status: Accepted

Solution code:
txt=raw_input()
i=0
j=len(txt)-1
x_count = 0
while i<j:
	if txt[i]==txt[j]:
		i+=1
		j-=1
	elif txt[i]=='x':
		i+=1
		x_count+=1
	elif txt[j]=='x':
		j-=1
		x_count+=1
	else:
		print -1
		exit(0)
print x_count

Submission status: Accepted

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

#リストsの先頭と末尾を比較
#先頭と末尾がx以外で異なるなら,-1を返す。
#先頭と末尾が同じなら先頭と末尾を移動させる。
#どちらか片方がxなら片方にxを追加し先頭と末尾を移動させたとするので最初にxだったほうだけ移動させる

#xabxa
while l != r:
    if s[l] != s[r]:
        if s[l] != "x" and s[r] != "x":
            count = -1
            break
        elif s[l] == "x" and s[r] != "x":
            l += 1
            count += 1
        elif s[r] == "x" and s[l] != "x":
            r -= 1
            count += 1
    elif s[l] == s[r]:
        if abs(l-r) == 1:
            break
        else:
            l += 1
            r -= 1

print(count)

Submission status: Accepted

Solution code:
s=raw_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' and s[j]!='x':
        ans=-1
        break
    elif s[i]=='x':
        ans+=1
        i+=1
    elif s[j]=='x':
        ans+=1
        j-=1
print ans

Submission status: Accepted

Solution code:
s = input()
t = [a for a in s if a!="x"]
u = []
tmp = 0
for a in s:
    if a == "x":
        tmp += 1
    else:
        u.append(tmp)
        tmp = 0
u.append(tmp)

if t != t[::-1]:
    print(-1)
else:
    ans = 0
    for i in range(len(u)//2):
        ans += abs(u[i] - u[-i-1])
    print(ans)

Submission status: Accepted

Solution code:
s = input()

cnt = 0
ans = 0

if len(s) == 1:
    cnt = 0
else:
    l = 0
    k = 0
    while True:
        if s[l] == s[-k-1]:
            l += 1
            k += 1
            if l + k >= len(s)-1:
                break
        elif s[l] == 'x':
            l += 1
            cnt += 1
            if l + k >= len(s)-1:
                break
        elif s[-k-1] == 'x':
            k += 1
            cnt += 1
            if l + k >= len(s)-1:
                break
        else:
            ans = -1
            break

if ans == -1:
    print(ans)
else:
    print(cnt)

Submission status: Accepted

Solution code:
import sys

s = input()
s_no_x = s.replace('x', '')
s_no_x_inv = s_no_x[::-1]

if not s_no_x == s_no_x_inv:
    print(-1)
    sys.exit()

count = 0
l = 0
r = len(s) - 1
while l < r:
    if l >= r:
        break
    if s[l] == s[r]:
        l += 1
        r -= 1
    if not s[l] == s[r]:
        count += 1
        if s[l] == 'x':
            l += 1
        else:
            r -= 1
print(count)

Submission status: Accepted

Solution code:
data = input()
tmp = data.replace("x", "")
c1 , c2, num = 0, -1, 0
if tmp == tmp[::-1]:
    while(c1 < len(data) + c2):
        if data[c1] == data[c2]:
            c1+=1
            c2-=1
        elif data[c2]=="x":
            c2-=1
            num+=1
        else:
            c1+=1
            num+=1
else:
    num = -1
print(num)

Submission status: Accepted

Solution code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import math
import itertools
import heapq
import numpy as np
from collections import OrderedDict, deque
from bisect import bisect_left, bisect_right, insort_left, insort_right
sys.setrecursionlimit(10000)

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]


class Dijkstra():
    def dijkstra(self, adj, start, goal=None):
        '''
        ダイクストラアルゴリズムによる最短経路を求めるメソッド
        入力
        adj: adj[i][j]の値が頂点iから頂点jまでの距離(頂点iから頂点jに枝がない場合，値はfloat('inf'))となるような2次元リスト(正方行列)
        start: 始点のID
        goal: オプション引数．終点のID
        出力
        goalを引数に持つ場合，startからgoalまでの最短経路を格納したリストを返す
        持たない場合は，startから各頂点までの最短距離を格納したリストを返す
        d = Dijkstra()
        d.dijkstra([[float('inf'), 2, 4, float('inf'), float('inf')], [2, float('inf'), 3, 5, float('inf')], [4, 3, float('inf'), 1, 4], [float('inf'), 5, 1, float('inf'), 3], [float('inf'), float('inf'), 4, 3, float('inf')]], 0)
        [0, 2, 4, 5, 8] # 例えば，始点0から頂点3までの最短距離は5となる
        d.dijkstra([[float('inf'), 2, 4, float('inf'), float('inf')], [2, float('inf'), 3, 5, float('inf')], [4, 3, float('inf'), 1, 4], [float('inf'), 5, 1, float('inf'), 3], [float('inf'), float('inf'), 4, 3, float('inf')]], 0, goal=4)
        [0, 2, 4] # 頂点0から頂点4までの最短経路は0 -> 2 -> 4となる
        '''
        num = len(adj)  # グラフのノード数
        dist = [float('inf') for i in range(num)]  # 始点から各頂点までの最短距離を格納する
        prev = [float('inf') for i in range(num)]  # 最短経路における，その頂点の前の頂点のIDを格納する

        dist[start] = 0
        q = []  # プライオリティキュー．各要素は，(startからある頂点vまでの仮の距離, 頂点vのID)からなるタプル
        heapq.heappush(q, (0, start))  # 始点をpush

        while len(q) != 0:
            prov_cost, src = heapq.heappop(q)  # pop

            # プライオリティキューに格納されている最短距離が，現在計算できている最短距離より大きければ，distの更新をする必要はない
            if dist[src] < prov_cost:
                continue

            # 他の頂点の探索
            for dest in range(num):
                cost = adj[src][dest]
                if cost != float('inf') and dist[dest] > dist[src] + cost:
                    dist[dest] = dist[src] + cost  # distの更新
                    heapq.heappush(q, (dist[dest], dest))  # キューに新たな仮の距離の情報をpush
                    prev[dest] = src  # 前の頂点を記録

        if goal is not None:
            return self.get_path(goal, prev)
        else:
            return dist

    def get_path(self, goal, prev):
        '''
        始点startから終点goalまでの最短経路を求める
        '''
        path = [goal]  # 最短経路
        dest = goal

        # 終点から最短経路を逆順に辿る
        while prev[dest] != float('inf'):
            path.append(prev[dest])
            dest = prev[dest]

        # 経路をreverseして出力
        return list(reversed(path))


class EndLoop(Exception):
    pass


def debug_print(L):
    for col in L:
        print(col)


def debug_print_joined(L):
    for col in L:
        print("".join(col))


def transpose_matrix(L):
    transposed = list(map(list, zip(*L)))
    return transposed

def kaibun(L):
    L2 = L.copy()
    L2.reverse()
    if L == L2:
        return True
    else:
        return False


def solve():
    s = deque(input())
    flag = True
    cnt = 0
    while s:
        if s[0] == s[-1]:
            s.pop()
            if not s:
                break
            s.popleft()
        else:
            if s[0] == "x":
                s.append("x")
                cnt += 1
            elif s[-1] == "x":
                s.appendleft("x")
                cnt += 1
            else:
                print("-1")
                flag = False
                break

    if flag:
        print(cnt)


solve()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from collections import deque
import sys

if __name__ == '__main__':
    s = list(input())
    que = deque(s)

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

    print(ans)

Submission status: Accepted

Solution code:
s = input()
ns = s.replace('x', '')
if s == s[::-1]:
    print(0)
elif ns != ns[::-1]:
    print(-1)
else:
    cnt = 0
    i = 0
    j = len(s)-1
    while(i<j):
        if s[i]=='x' and s[j]!='x':
            cnt += 1
            j += 1
        elif s[i]!='x' and s[j]=='x':
            cnt += 1
            i -= 1
        i += 1
        j -= 1
    print(cnt)

Submission status: Accepted

Solution code:
s = input()
ns = s.replace('x', '')
if s == s[::-1]:
	print(0)
elif ns != ns[::-1]:
	print(-1)
else:
	cnt = 0
	i = 0
	j = len(s)-1
	while(i<j):
		if s[i]=='x' and s[j]!='x':
			cnt += 1
			j += 1
		elif s[i]!='x' and s[j]=='x':
			cnt += 1
			i -= 1
		i += 1
		j -= 1
	print(cnt)

Submission status: Accepted

Solution code:
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
INF = float("inf")


def main():
    s = input()
    ans = 0

    left, right = 0, len(s) - 1
    while left < right:
        l, r = s[left], s[right]
        if l == r:
            left += 1
            right -= 1
        elif l != "x" and r != "x":
            ans = -1
            break
        elif l == "x" and r != "x":
            ans += 1
            left += 1
        elif l != "x" and r == "x":
            ans += 1
            right -= 1

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s = input()

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

print(ans)

Submission status: Accepted

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

S = input()
r = len(S) - 1
l = 0
cnt = 0
f = True
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:
        f = False
        break
if f:
    print(cnt)
else:
    print(-1)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:

s = input()

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

Submission status: Accepted

Solution code:
s = input()
len_s = len(s)
l_index = 0
r_index = len_s - 1
counter = 0
while l_index < r_index:
    if s[l_index] == s[r_index]:
        l_index += 1
        r_index -= 1
    elif s[l_index] == "x":
        counter += 1
        l_index += 1
    elif s[r_index] == "x":
        counter += 1
        r_index -=1
    else:
        counter = -1
        break
print(counter)

Submission status: Accepted

Solution code:
import sys
S = str(input())
i = 0
j = len(S) - 1
c = 0
while(True):
    if i >= j:
        break
    if (S[i] == S[j]):
        i += 1
        j -= 1
    else:
        if (S[i] == 'x'):
            i += 1
            c += 1
        elif (S[j] == 'x'):
            j -= 1
            c += 1
        else:
            print('-1')
            sys.exit()
print(c)

Submission status: Accepted

Solution code:
use = input()

total = 0
p = 0
p1 = len(use) - 1
while p < p1:
	if use[p] == use[p1]:
		p += 1
		p1 -= 1
	elif use[p] == "x":
		p += 1
		total += 1
	elif use[p1] == "x":
		p1 -= 1
		total += 1
	else:
		total = -1
		break
print(total)

Submission status: Accepted

Solution code:
s = input()

if s == s[::-1]:
    print(0)
else:
    t = s.replace('x', '')
    if t != t[::-1]:
        print(-1)
    else:
        f = 0
        b = len(s) - 1
        count = 0
        while True:
            if s[f] == s[b]:
                f += 1
                b -= 1
            else:
                count += 1
                if s[f] == "x":
                    f += 1
                elif s[b] == "x":
                    b -= 1
            if f >= b:
                break
        print(count)

Submission status: Accepted

Solution code:
S = input()

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

print(ret)

Submission status: Accepted

Solution code:
n = input()

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

ncr = nc[::-1]

ans = -1

if ncr == nc:
    ans = 0
    nl = list(n)
    lenn = len(n)
    i = 0
    j = 1
    ri = 0
    le = 0
    while(1):
        if i >= lenn-(j):break
        if n[i] == n[lenn-(j)]:
            i += 1
            j += 1
        else:
            if n[i] == "x":
                i +=1
            else:
                j +=1
            ans += 1

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""code-fes-2017-qual-c-c"""


import sys

OP_NUM = 0

def solve(s):
    """Solve."""
    global OP_NUM

    if len(s) == 0:
        return ""
    if len(s) == 1:
        return ""

    if s[0] == 'x':
        if s[-1] == 'x':
            return s[1:-1]
        OP_NUM += 1
        return s[1:]

    if s[0] == s[-1]:
        return s[1:-1]
    if 'x' == s[-1]:
        OP_NUM += 1
        return s[:-1]

    return None


def main():
    """Main function."""
    s = input()

    while s:
        s = solve(s)
        if s is None:
            print(-1)
            sys.exit(0)

    print(OP_NUM)

if __name__ == '__main__':
    sys.exit(main())

Submission status: Accepted

Solution code:

# -*- coding: utf-8 -*-
s = input()

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

if i == j:
    if s[:i].replace("x", "") == s[i+1:][::-1].replace("x", ""):
        print(result)
    else:
        print(-1)
else:
    if s[:j+1].replace("x", "") == s[i:][::-1].replace("x", ""):
        print(result)
    else:
        print(-1)

Submission status: Accepted

Solution code:
import numpy as np
s = input()
s_list = list(s)
s_array = np.array(s_list)
s_without_x_ar = s_array[s_array != "x"]

if (s_without_x_ar != s_without_x_ar[::-1]).any():
    print(-1)
else:
    kw_count = len(s_without_x_ar)
    if kw_count == 0:
        print(0)
    elif kw_count % 2 == 0:
        half_s_wox_left = s_without_x_ar[:int(kw_count/2)]
        lastw_count = len(half_s_wox_left[half_s_wox_left==half_s_wox_left[-1]])
        check_last_idx = np.where(s_array == half_s_wox_left[-1])[0][lastw_count-1]
        half_array = s_array[:check_last_idx+1]
        
        
        a = np.where(half_array!="x")[0]
        a = np.insert(a,0,-1)
        left_count_ar = a[1:] - a[:-1] - 1


        # right
        half_s_wox_right = s_without_x_ar[int(kw_count/2):]
        half_s_wox_right_back = half_s_wox_right[::-1]
        s_array_back = s_array[::-1]

        lastw_count = len(half_s_wox_right_back[half_s_wox_right_back==half_s_wox_right_back[-1]])
        check_last_idx = np.where(s_array_back == half_s_wox_right_back[-1])[0][lastw_count-1]

        half_array = s_array_back[:check_last_idx+1]
        
        a = np.where(half_array!="x")[0]
        a = np.insert(a,0,-1)
        right_count_ar = a[1:] - a[:-1] - 1
        
        print(np.abs(right_count_ar - left_count_ar).sum())
        
    else:
        half_s_wox_left = s_without_x_ar[:int(kw_count//2+1)]
        lastw_count = len(half_s_wox_left[half_s_wox_left==half_s_wox_left[-1]])
        check_last_idx = np.where(s_array == half_s_wox_left[-1])[0][lastw_count-1]
        half_array = s_array[:check_last_idx+1]
        
        
        a = np.where(half_array!="x")[0]
        a = np.insert(a,0,-1)
        left_count_ar = a[1:] - a[:-1] - 1


        # right
        half_s_wox_right = s_without_x_ar[int(kw_count//2):]
        half_s_wox_right_back = half_s_wox_right[::-1]
        s_array_back = s_array[::-1]

        lastw_count = len(half_s_wox_right_back[half_s_wox_right_back==half_s_wox_right_back[-1]])
        check_last_idx = np.where(s_array_back == half_s_wox_right_back[-1])[0][lastw_count-1]

        half_array = s_array_back[:check_last_idx+1]
        
        a = np.where(half_array!="x")[0]
        a = np.insert(a,0,-1)
        right_count_ar = a[1:] - a[:-1] - 1
        
        print(np.abs(right_count_ar - left_count_ar).sum())

Submission status: Accepted

Solution code:
S = input()

st = 0
en = len(S) - 1
ans = 0
while st < en:
    if S[st] == S[en]:
        st += 1
        en -= 1
    elif S[st] == 'x':
        ans += 1
        st += 1
    elif S[en] == 'x':
        ans += 1
        en -= 1
    else:
        ans = -1
        break

print(ans)

Submission status: Accepted

Solution code:
import math as mt
import numpy as np

string = input()
collect = []
word = ''
count = 0
n = len(string)
i = 0
for x in string:
    if x != 'x':
        word += x
        collect.append(count)
        if i == n-1:
            collect.append(0)
        count = 0
    elif i == n-1:
        count += 1
        collect.append(count)
    else:
        count += 1
    i += 1

nl = len(word) - 1
i = 0
while i < nl:
    if word[i] != word[nl]:
        print(-1)
        exit()
    i += 1
    nl -=  1
nl = len(collect) - 1
i = 0
out = 0
while i < nl:
    out += np.abs(collect[i] - collect[nl])
    i += 1
    nl -= 1
print(out)

Submission status: Accepted

Solution code:
s = input()


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

for i in range( len(s) ):
	if r <= l:
		break
	if s[l] == s[r]:
		l += 1
		r -= 1
	else:
		if (s[l] != 'x' and s[r] != 'x'):
			ans = -1
			break
		else:
			ans += 1
			if s[l] == 'x':
				l += 1
			else:
				r -= 1
print(ans)

Submission status: Accepted

Solution code:
s = raw_input()
sr = s[::-1]
sx = s.replace("x","")

if s == sr:
  print 0
  exit(0)

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

x1 = []
x2 = []
pos1 = 0
pos2 = 0

for a in s:
  if a != "x":
    x1.append(pos1)
    pos1 = 0
  else:
    pos1 += 1
x1.append(pos1)

for a in sr:
  if a != "x":
    x2.append(pos2)
    pos2 = 0
  else:
    pos2 += 1
x2.append(pos2)

count = 0
for a in range(len(x1)):
  count += abs(x1[a]-x2[a])

print count/2

Submission status: Accepted

Solution code:
a=input()
b=a[::-1]
count=0
no=1
la=0
lb=0

while la+lb+2<=len(a):
#    print(a[la],b[lb])
    if a[la]==b[lb]:
        la=la+1
        lb=lb+1
    else:
        if a[la]=="x":
            count=count+1
            la=la+1
        elif b[lb]=="x":
            count=count+1
            lb=lb+1
        else:
            print(-1)
            no=0
            break
if no==1:
    print(count)