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: Runtime Error

Solution code:
S = list(input())
X = []
NX = ""

for i in range(len(S)):
    if S[i] == "x": X.append(i)
    else: NX += S[i]
    
NXr = ""
for i in reversed(range(len(NX))): NXr += NX[i]

if NXr != NX: print(-1)
else:
    mid = S.index(NX[(len(NX) - 1)//2])
    Xleft, Xright = set(), set()
    for x in X:
        if x < mid: Xleft |= {mid-x}
        else: Xright |= {x-mid}
    print(len(Xleft ^ Xright))

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
#define LL long long
using namespace std;
string	st;
int	ans;
bool	flag = true;
int main()
{
	cin >> st;
	int L=0,R = st.size() - 1;
	while ( L <= R )
	{
		if ( st[L] == st[R] ) {L++,R--;continue;}
		if ( st[L] == 'x' ) {L++,ans++;continue;}
		if ( st[R] == 'x' ) {R--,ans++;continue;}
		flag = false; break;
	}
	ans = flag ? ans : -1;
	cout << ans ;
	return(0);
}

Submission status: Runtime Error

Solution code:
import math
s = list(str(input()))
lis = ""
li = ""
num = 0
cou = [0 for i in range(26)]
for i in range(len(s)):
  if s[i] != "x":
    lis += s[i]
    li = s[i] + li
  else:
    num += 1
if lis != li:
  print(-1)
  exit()
point = lis[len(lis)//2]
ss = ["1"]
tt = ["1"]
nu = 0
while s[nu] != point:
  ss.append(s[nu])
  nu += 1
nu = 0
while s[-1-nu] != point:
  tt.append(s[-1-nu])
  nu += 1
ans = 0
for i in range(max(len(ss),len(tt))):
  try:
    if ss[i] != tt[i]:
      ans += 1
  except:
    ans += 1
print(ans)

Submission status: Runtime Error

Solution code:
import math
s = list(str(input()))
lis = ""
li = ""
num = 0
cou = [0 for i in range(26)]
for i in range(len(s)):
  if s[i] != "x":
    lis += s[i]
    li = s[i] + li
  else:
    num += 1
if lis != li:
  print(-1)
  exit()
point = lis[len(lis)//2]
ss = ["1"]
tt = ["1"]
nu = 0
while s[nu] != point:
  ss.append(s[nu])
  nu += 1
nu = 0
while s[-1-nu] != point:
  tt.append(s[-1-nu])
  nu += 1
ans = 0
for i in range(max(len(ss),len(tt))):
  try:
    if ss[i] != tt[i]:
      ans += 1
  except:
    ans += 1
print(ans,ss,tt)

Submission status: Runtime Error

Solution code:
import math
s = list(str(input()))
lis = ""
li = ""
num = 0
cou = [0 for i in range(26)]
for i in range(len(s)):
  if s[i] != "x":
    lis += s[i]
    li = s[i] + li
  else:
    num += 1
if lis != li:
  print(-1)
  exit()
point = lis[len(lis)//2]
ss = []
tt = []
nu = 0
while s[nu] != point:
  ss.append(s[nu])
  nu += 1
nu = 0
while s[-1-nu] != point:
  tt.append(s[-1-nu])
  nu += 1
ans = 0
for i in range(len(ss)):
  if ss[i] != tt[i]:
    ans += 1
print(ans)

Submission status: Runtime Error

Solution code:
import math
s = list(str(input()))
lis = ""
li = ""
num = 0
cou = [0 for i in range(26)]
for i in range(len(s)):
  if s[i] != "x":
    lis += s[i]
    li = s[i] + li
  else:
    num += 1
if lis != li:
  print(-1)
  exit()
point = lis[len(lis)//2]
ss = []
tt = []
nu = 0
while s[nu] != point:
  ss.append(s[nu])
  nu += 1
nu = 0
while s[-1-nu] != point:
  tt.append(s[-1-nu])
  nu += 1
ans = 0
for i in range(n):
  if ss[i] != tt[i]:
    ans += 1
print(ans)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
s = input()
go = []
back = []
start = 0
end = len(s)-1
res = 0
while start<=end:
    gox = 0
    backx = 0
    while s[start] == 'x' and start<=end:
        start+=1
        gox += 1
    while s[end] == 'x'and start<=end:
        end -= 1
        backx +=1
    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: Runtime Error

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: Runtime Error

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: Runtime Error

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]:
        l += 1
        r -= 1

print(count)

Submission status: Runtime Error

Solution code:
def calc(value):
    res = 0
    while True:
        if len(value) == 1:
            break
        elif value[0] != value[-1] and value[0] != "x" and value[-1] != "x":
            res = -1
            break
        elif value[0] == value[-1]:
            value.pop(0)
            value.pop()
        else:
            value.extend("x") if value[0] == "x" else value.insert(0, "x")
            value.pop(0)
            value.pop()
            res += 1
    return res


def main():
    value = list(input())
    print(calc(value))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def calc(value):
    res = 0
    while True:
        if len(value) == 1:
            break
        elif value[0] != value[-1] and value[0] != "x" and value[-1] != "x":
            res = -1
            break
        elif value[0] == value[-1]:
            value.pop(0)
            value.pop()
        else:
            value.extend("x") if value[0] == "x" else value.insert(0, "x")
            res += 1
    return res


def main():
    value = list(input())
    print(calc(value))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
s = input()
len_s = len(s)
l_index = 0
r_index = 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: Runtime Error

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: Runtime Error

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: Runtime Error

Solution code:
if __name__ == "__main__":
    words=input()
    words_list=list(words)

    check_words = list(words.replace('x', ''))

    if len(check_words)%2==0:
        split_point=int(len(check_words)/2)
        if split_point!=1:
            split_point=split_point-1
        for (x,y) in zip(check_words[:split_point],
                         check_words[-split_point:]):
            if x!=y:
                print(-1)
                break
    else:
        split_point=int(len(check_words)/2)
        for (x,y) in zip(check_words[:split_point],
                         check_words[-split_point:]):
            if x!=y:
                print(-1)
                break

    # xを足す
    cnt=0
    head=0
    tail=len(words_list)-1
    while(True):
        if head == tail:
            break
        else:
            cnt=cnt+1
        if words_list[head]==words_list[tail]:
            head=head+1
            tail=tail-1
            cnt=cnt-1
        elif words_list[head]=='x':
            words_list.insert(tail+1, 'x')
            tail=tail+1
        elif words_list[tail]=='x':
            words_list.insert(head, 'x')
            head=head+1
    print(cnt)

Submission status: Runtime Error

Solution code:
import sys

def kaibun(S):
    mid = len(S)//2
    if len(S) % 2 == 0:
        left = S[:mid]
        right = S[mid:][::-1]
    else:
        left = S[:mid]
        right = S[mid+1:][::-1]
    if left==right:
        return 1
    else:
        return 0

S = input()
s = ""
position = []
for i in range(len(S)):
    if S[i] != "x":
        s += S[i]
        position.append(i)

if kaibun(s) == 0:
    print(-1)
elif len(S) == 1:
    print(0)
else:
    count = 0
    if len(position)%2 == 1:
        mid = position[len(s)//2]
        left = S[:mid]
        right = S[mid+1:][::-1]
    else:
        mid1 = position[len(s)//2]
        mid2 = position[len(s)//2]
        left = S[:mid1]
        right = S[mid2+1:][::-1]

    if len(left)== 0 or len(right)==0:
        print(max(len(left), len(right)))
        sys.exit()
              
    
    lsta = 0
    rsta = 0
    while(1):
        if left[lsta] != right[rsta]:
            if left[lsta] == "x":
                lsta += 1
                count += 1
            else:
                rsta += 1
                count += 1
        else:
            if lsta != len(left)-1:
                lsta += 1
            if rsta != len(right)-1:
                rsta += 1
        if lsta == len(left)-1:
            count += lsta - rsta
            break
        if rsta == len(right)-1:
            count += rsta - lsta
            break
    print(count)

Submission status: Runtime Error

Solution code:
s = input()
sList = []

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

while True:
    if 'x' in sList:
        sList.remove('x')
    else:
        break

if len(sList)%2==0:
    number = len(sList)//2
else:
    number = (len(sList)+1)//2        
end = 0
for i in range(number):
    if sList[i]!=sList[-(i+1)]:
        print(-1)
        end = 1
        break


        
count = 0
F0 = 0
R0 = 0
if end == 0:
    sListF = []
    sListR = []
    
    for i in range(len(s)):
        sListF.append(s[i])
        sListR.append(s[-(i+1)])
        
    while True:
        if 'x' in sList:
            sList.remove('x')
        else:
            break
    
    
    
    for i in range(number):
        F = sListF.index(sList2[i])-F0
        R = sListR.index(sList2[i])-R0
        count += max([F, R])-min([F, R])
        F0 += F
        R0 += R


    
    print(count)

Submission status: Runtime Error

Solution code:
a=list(raw_input())
b=[]
e=0
for i in a:
    if i!="x":
        b.append(i)
    else:
        e+=1

if len(b)%2==0:
    c=len(b)/2
    amd=1
else:
    c=len(b)/2+1
    amd=0
d=len(b)

ch=0
for i in range(c):
    if b[i]!=b[d-1-i]:
        ch=1
if ch==1:
    print -1
else:
    if e==0:
        print 0
    else:
        pre=b[0:c]
        las=b[c:d]
        mode=pre
        ord=0
        x_order=[]
        skip=0
        exc=0
        for i in range(len(a)):
            if a[i]=="x":
                if skip==0:
                    x_order.append(i)
                else:
                    exc+=1
            elif a[i]==mode[ord]:
                ord+=1
                if ord==c and mode==pre:
                    mode=las
                    ord=0
                    poi=i
                    if amd==1:
                        skip=1
                elif ord==1 and mode==las:
                    skip=0
        print x_order
        x_order_rev=[]
        if exc % 2 == 0:
            poi += exc / 2
        else:
            c += exc / 2 + 1
        d = len(b)
        for i in range(e-exc):
            x_order[i]-=poi
            x_order_rev.append(x_order[e-exc-i-1]*-1)
        cou=0
        for i in range(e-exc):
            if x_order[i]==x_order_rev[i]:
                cou+=1
        print e-exc-cou

Submission status: Runtime Error

Solution code:
s = input()

x = -1

if len(s) == 1:
    x = 0
else:
    s2 = s.replace('x', '')

    if len(s2) % 2 == 0:
        flg = True
    else:
        flg = False

    nf = len(s2) // 2

    if flg:
        s2_pre = s2[:nf+1]
        s2_post = s2[nf+1:]
    else:
        s2_pre = s2[:nf]
        s2_post = s2[nf+1:]

    if s2_pre == s2_post[::-1]:
        cnt_s = 0
        cnt_s2 = 0
        while True: # 元の文字列の中心を求める
            if s[cnt_s] == 'x':
                cnt_s += 1
            if s[cnt_s] == s2[cnt_s2]:
                cnt_s += 1
                cnt_s2 += 1
            if cnt_s2 >= nf:
                break

        if len(s) % 2 == 0:
            s_pre = s[:cnt_s+1]
            s_post = s[cnt_s+1:]
        else:
            s_pre = s[:cnt_s]
            s_post = s[cnt_s+1:]

        s_postR = s_post[::-1]

        s_pre = list(s_pre)
        s_postR =  list(s_postR)

        cnt = 0
        cnt_pre = 0
        cnt_post = 0
        while True:
            try:
                if s_pre[cnt_pre] == s_postR[cnt_post]:
                    cnt_pre += 1
                    cnt_post += 1
            except IndexError:
                pass
            
            if len(s_pre) > cnt_pre:
                if s_pre[cnt_pre] == 'x':
                    s_postR.insert(cnt_post, 'x')
                    cnt_pre += 1
                    cnt_post += 1
                    cnt += 1
            elif len(s_postR) > cnt_post:
                if str(s_pre) == str(s_postR):
                    break
                else:
                    s_pre.insert(cnt_pre, s_postR[cnt_post])
                    cnt_pre += 1
                    cnt_post += 1
                    cnt += 1
                    
            if len(s_postR) > cnt_post:
                if s_postR[cnt_post] == 'x':
                    s_pre.insert(cnt_pre, 'x')
                    cnt_pre += 1
                    cnt_post += 1
                    cnt += 1
            elif len(s_pre) > cnt_pre:
                if str(s_pre) == str(s_postR):
                    break
                else:
                    s_postR.insert(cnt_post, s_pre[cnt_pre])
                    cnt_pre += 1
                    cnt_post += 1
                    cnt += 1

            if str(s_pre) == str(s_postR):
                break

        x = cnt
    
print(x)

Submission status: Runtime Error

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 solve(s[1:-1])
        OP_NUM += 1
        return solve(s[1:])

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

    return None


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

    forward = solve(s)
    if forward is None:
        print(-1)
    else:
        print(OP_NUM)


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

Submission status: Runtime Error

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 % 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: Runtime Error

Solution code:
from collections import deque


def insert_c(s, idx, c):
    return s[:idx] + c + s[idx:]


def calc(s):
    if s == s[::-1]:
        return 0
    if s.replace('x', '') != s.replace('x', '')[::-1]:
        return -1
    # import ipdb;ipdb.set_trace()
    revs = deque(s[::-1])
    s = deque(s)
    cnt = 0
    o_gap, r_gap = 0, 0
    idx = 0
    while idx + o_gap <= len(s) / 2 and idx + r_gap <= len(s) / 2:
        print(cnt, o_gap, r_gap, idx)
        print(' ' + ''.join(s) + '\n', ''.join(revs))
        print(' ' + ' ' * idx + '^')
        if s[idx + o_gap] != revs[idx + r_gap]:
            # print(s[idx + o_gap], revs[idx + r_gap])
            if s[idx + o_gap] == 'x':
                revs.insert(idx, 'x')  # = insert_c(revs, idx, 'x')
                s.insert(len(s)-idx, 'x')
                # r_gap -= 1
            elif revs[idx + r_gap] == 'x':
                s.insert(idx, 'x')  # = insert_c(s, idx, 'x')
                revs.insert(len(revs)-idx, 'x')
                # o_gap -= 1
            cnt += 1
        else:
            idx += 1
    return cnt


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


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from collections import Counter

S = input()
s = list(S)

counter = Counter(s)
odd = 0
flag = True

for k,v in counter.items():
    #偶奇性の判定
    if k != 'x':
        if v%2 == 1:
            odd += 1
            mid = k
    if odd >= 2:#奇数個ある小文字が複数ある場合できない
        flag = False

#"x"を除いた時の回文判定
if flag:
    s_sub = S.replace("x","")

    indexes = [i for i,x in enumerate(s_sub)if x == mid]
    center = indexes[len(indexes)//2 ]#奇数個ある数の中央のindexをとる
    if s_sub[center-1::-1] != s_sub[center+1:]:
        flag == False

#各アルファベットの距離判定
    if flag:
        indexes = [i for i,x in enumerate(s) if x == mid]
        center = indexes[len(indexes)//2 ]
        count = 0
        hidari = []
        migi = []

        for i in range(0,center)[::-1]:
            if s[i] == 'x':
                count += 1
            else:
                hidari.append(count)
                count = 0
    
        hidari.append(count)
        count = 0

        for i in range(center+1,len(s)):
            if s[i] == 'x':
                count += 1
            
            else:
                migi.append(count)
                count = 0

        migi.append(count)
        count = 0

        ans = 0
        for i in range(len(hidari)):
            ans += abs(hidari[i]-migi[i])
            
        print(ans)
 

else:
    print(-1)

Submission status: Runtime Error

Solution code:
# coding: utf-8
S = raw_input()


def split(string):
    mid = len(string) / 2
    if len(string) % 2:
        left = string[:mid]
        center = string[mid]
        right = (string[mid + 1:])[::-1]
    else:
        left = string[:mid]
        center = ''
        right = (string[mid:])[::-1]
    return left, center, right


def join(left, center, right):
    return left + center + right[::-1]


def check(string, count):
    left, center, right = split(string)

    # check done
    if left == right:
        return count

    # insert x
    for i in range(len(left)):
        if left[i] != right[i]:
            if left[i:].count('x') < right[i:].count('x'):
                left = left[:i] + 'x' + left[i:]
            else:
                right = right[:i] + 'x' + right[i:]
            count += 1

    string = join(left, center, right)
    return check(string, count)


# check char mismatch
s = ''.join([c for c in S if c != 'x'])
left, center, right = split(s)
left_count = {c: left.count(c) for c in left}
right_count = {c: right.count(c) for c in right}
linr = sum(c not in right_count or v != right_count[c]
           for c, v in left_count.iteritems() if c != 'x')
rinl = sum(c not in left_count or v != left_count[c]
           for c, v in right_count.iteritems() if c != 'x')

if linr + rinl > 1:
    print -1
elif len(S) == 0:
    print 0
else:
    print check(S, 0)

Submission status: Runtime Error

Solution code:
from collections import deque


def insert_c(s, idx, c):
    return s[:idx] + c + s[idx:]


def calc(s):
    if s == s[::-1]:
        return 0
    if s.replace('x', '') != s.replace('x', '')[::-1]:
        return -1
    # import ipdb;ipdb.set_trace()
    revs = deque(s[::-1])
    s = deque(s)
    cnt = 0
    o_gap, r_gap = 0, 0
    idx = 0
    while idx + o_gap <= len(s) / 2 and idx + r_gap <= len(s) / 2:
        # print(cnt, o_gap, r_gap, idx)
        # print(s[idx + o_gap], revs[idx + r_gap], s, revs)
        if s[idx + o_gap] != revs[idx + r_gap]:
            # print(s[idx + o_gap], revs[idx + r_gap])
            if s[idx + o_gap] == 'x':
                cnt += 1
                revs.insert(idx, 'x')  # = insert_c(revs, idx, 'x')
                s.insert(len(s)-idx, 'x')
                # r_gap -= 1
            elif revs[idx + r_gap] == 'x':
                cnt += 1
                s.insert(idx, 'x')  # = insert_c(s, idx, 'x')
                revs.insert(len(revs)-idx, 'x')
                # o_gap -= 1
        else:
            idx += 1
    return cnt


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


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# coding: utf-8
S = raw_input()


def split(string):
    mid = len(string) / 2
    if len(string) % 2:
        left = string[:mid]
        center = string[mid]
        right = (string[mid + 1:])[::-1]
    else:
        left = string[:mid]
        center = ''
        right = (string[mid:])[::-1]
    return left, center, right


def join(left, center, right):
    return left + center + right[::-1]


def check(string, count):
    left, center, right = split(string)

    # check done
    if left == right:
        return count

    # insert x
    for i in range(len(left)):
        print i, left[i], right[i]
        if left[i] != right[i]:
            if left[i:].count('x') < right[i:].count('x'):
                left = left[:i] + 'x' + left[i:]
            else:
                right = right[:i] + 'x' + right[i:]
            count += 1

    string = join(left, center, right)
    return check(string, count)


# check char mismatch
s = ''.join([c for c in S if c != 'x'])
left, center, right = split(s)
left_count = {c: left.count(c) for c in left}
right_count = {c: right.count(c) for c in right}
linr = sum(c not in right_count or v != right_count[c]
           for c, v in left_count.iteritems() if c != 'x')
rinl = sum(c not in left_count or v != left_count[c]
           for c, v in right_count.iteritems() if c != 'x')

if linr + rinl > 1:
    print -1
elif len(S) == 0:
    print 0
else:
    print check(S, 0)

Submission status: Runtime Error

Solution code:
from collections import Counter

S = input()
s = list(S)

counter = Counter(s)
odd = 0
flag = True

for k,v in counter.items():
    #偶奇性の判定
    if k != 'x':
        if v%2 == 1:
            odd += 1
            mid = k
    if odd >= 2:#奇数個ある小文字が複数ある場合できない
        flag = False

#"x"を除いた時の回文判定
if flag:
    s_sub = S.replace("x","")

    indexes = [i for i,x in enumerate(s_sub)if x == mid]
    center = indexes[len(indexes)//2 ]#奇数個ある数の中央のindexをとる
    if s_sub[center-1::-1] != s_sub[center+1:]:
        flag == False

#各アルファベットの距離判定
if flag:
    indexes = [i for i,x in enumerate(s) if x == mid]
    center = indexes[len(indexes)//2 ]
    count = 0
    hidari = []
    migi = []

    for i in range(0,center)[::-1]:
        if s[i] == 'x':
            count += 1
        else:
            hidari.append(count)
            count = 0
    
    hidari.append(count)
    count = 0

    for i in range(center+1,len(s)):
        if s[i] == 'x':
            count += 1
            
        else:
            migi.append(count)
            count = 0

    migi.append(count)
    count = 0

    ans = 0
    for i in range(len(hidari)):
        ans += abs(hidari[i]-migi[i])
            
    print(ans)
 

else:
    print(-1)

Submission status: Runtime Error

Solution code:
import sys
s=raw_input()
l=len(s)
sa=[]
cb=[]
ca=[]
for n in range(l):
 an=s[n]
 if an!="x":
  sa.append(n)
  ca.append(an)
 bn=s[l-n-1]
 if bn!="x":
  cb.append(bn)
pnt=sa[int((len(sa)+1)/2)-1]
if ca!=cb:
 print "-1"
 sys.exit()
ha=s[:pnt+1]
bb=s[::-1]
hb=bb[:(l-pnt)]
count=0
lista=[]
listb=[]
for ch in ha:
 if ch=="x":
  count+=1
 else:
  lista.append(count)
  count=0
for ch in hb:
 if ch=="x":
  count+=1
 else:
  listb.append(count)
  count=0
count=0
for x in range(len(lista)):
 count+=abs(lista[x]-listb[x])
print count

Submission status: Runtime Error

Solution code:
from collections import deque


def insert_c(s, idx, c):
    return s[:idx] + c + s[idx:]


def calc(s):
    if s == s[::-1]:
        return 0
    if s.replace('x', '') != s.replace('x', '')[::-1]:
        return -1
    # import ipdb;ipdb.set_trace()
    revs = deque(s[::-1])
    s = deque(s)
    cnt = 0
    o_gap, r_gap = 0, 0
    idx = 0
    while idx + o_gap <= len(s) / 2 and idx + r_gap <= len(s) / 2:
        # print(cnt, o_gap, r_gap, idx)
        # print(s[idx + o_gap], revs[idx + r_gap])
        if s[idx + o_gap] != revs[idx + r_gap]:
            # print(s[idx + o_gap], revs[idx + r_gap])
            if s[idx + o_gap] == 'x':
                cnt += 1
                revs.insert(idx, 'x')  # = insert_c(revs, idx, 'x')
                idx -= 1
                # r_gap -= 1
            elif revs[idx + r_gap] == 'x':
                cnt += 1
                s.insert(idx, 'x')  # = insert_c(s, idx, 'x')
                # o_gap -= 1
                idx -= 1
        idx += 1
    return cnt


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


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
s=raw_input()
l=len(s)
sa=[]
sb=[]
ca=[]
cb=[]
for n in range(l):
 an=s[n]
 if an!="x":
  sa.append((n,an))
  ca.append(an)
 bn=s[l-n-1]
 if bn!="x":
  sb.append((l-n-1,bn))
  cb.append(bn)
pnt=sa[int((len(sa)+1)/2)-1][0]
if ca!=cb:
 print "-1"
 sys.exit()
ha=s[:pnt+1]
bb=s[::-1]
hb=bb[:(l-pnt)]
count=0
lista=[]
listb=[]
for ch in ha:
 if ch=="x":
  count+=1
 else:
  lista.append(count)
  count=0
for ch in hb:
 if ch=="x":
  count+=1
 else:
  listb.append(count)
  count=0
count=0
for x in range(len(lista)):
 count+=abs(lista[x]-listb[x])
print count

Submission status: Runtime Error

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_)/2 + 1:
            judge = 2

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

Submission status: Runtime Error

Solution code:
from collections import deque


def insert_c(s, idx, c):
    return s[:idx] + c + s[idx:]


def calc(s):
    if s == s[::-1]:
        return 0
    if s.replace('x', '') != s.replace('x', '')[::-1]:
        return -1
    # import ipdb;ipdb.set_trace()
    revs = deque(s[::-1])
    s = deque(s)
    cnt = 0
    o_gap, r_gap = 0, 0
    idx = 0
    while idx + o_gap <= len(s) / 2  and idx + r_gap <= len(s) / 2 :
        # print(cnt, o_gap, r_gap, idx)
        # print(s[idx + o_gap], revs[idx + r_gap])
        if s[idx + o_gap] != revs[idx + r_gap]:
            # print(s[idx + o_gap], revs[idx + r_gap])
            if s[idx + o_gap] == 'x':
                cnt += 1
                revs.insert(idx, 'x') # = insert_c(revs, idx, 'x')
                # r_gap -= 1
            elif revs[idx + r_gap] == 'x':
                cnt += 1
                s.insert(idx, 'x') # = insert_c(s, idx, 'x')
                # o_gap -= 1
        idx += 1
    return cnt


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


if __name__ == '__main__':
    main()