回文索引数
题目描述
输入N+1行,第一行为整数N(大于等于1),表示测试数据的组数,后面N行仅由小写字母组成的字符串。现在请找出一个位置,删掉那个字母之后,字符串变成回文。请放心总会有一个合法的解。如果给定的字符串已经是一个回文串,那么输出-1。
解题思路
根据题目不考虑删除元素后不是回文串的情况。
1.判断字符串是否是回文,是打印-1,不是就继续
2.循环删除字符串的一个元素,删除后的新字符串如果是回文就打印删除的索引值,并跳出循环;如果不是回文就继续
python代码实现
# -*- coding:utf-8 -*-
def isPalindrome(str):
str1 = str[::-1]
if str == str1:
return True
else:
return False
def str_remove(str, idx):
tmpList = list(str)
tmpList.pop(idx)
return "".join(tmpList)
num = int(input())
a = []
for i in range(num):
a.append(input())
for x in a:
if isPalindrome(x):
print("-1")
else:
for i in range(len(x)):
xNew = str_remove(x, i)
if isPalindrome(xNew):
print(i)
break
else:
continue