[编程题]回文数索引
给定一个仅由小写字母组成的字符串。现在请找出一个位置,删掉那个字母之后,字符串变成回文。请放心总会有一个合法的解。如果给定的字符串已经是一个回文串,那么输出-1。
输入描述:
第一行包含T,测试数据的组数。后面跟有T行,每行包含一个字符串。
输出描述:
如果可以删去一个字母使它变成回文串,则输出任意一个满足条件的删去字母的位置(下标从0开始)。例如:
bcc
我们可以删掉位置0的b字符。
输入例子1:
3 aaab baa aaa
输出例子1:
3 0 -1
思路
主要使用reverse()
,将输入的字符s
,反转后与原字符比较。。。
代码
#include<iostream>
#include <string>
#include<algorithm>
using namespace std;
inline bool isPalindrome(string s) {
string s1 = s;
reverse(s1.begin(), s1.end());
if (s1 == s)
return true;
else
return false;
}
int main()
{
int t;
cin >> t;
string s;
for (int i = 0; i < t; i++) {
cin >> s;
if (isPalindrome(s)) {
cout << -1 << endl;
continue;
}
for (int j = 0; j < s.length(); j++) {
string s1(s);
s1 = s1.erase(j,1);
if (isPalindrome(s1)) {
cout << j << endl;
break;
}
}
}
return 0;
}