问题描述:
如果一个字符串正反都是同样的,那么称这个字符串是回文串,比如“level”或者“noon”等等就是回文串。现在给出一个字符串,在字符串后面添加一些字符,让它成为一个回文字符串。
注意:输入的字符串只包含小写字母。
Input
输入数据的第一行n,表示字符串长度(1<=n<=100)。
接下来一行是一个长度为n的字符串。
Output
第一行输出一个整数,表示最少需要添加的字符个数。
第二行输出加入字符后的回文字符串。
解题思路:
将原字符数组倒置,找出与原数组最大的相同连续序列(原数组连续序列必须位于数组末尾)字符的个数,用总的字符个数减去相同的个数就是需要添加的个数
#include<cstdio>
#include<string>
#include<algorithm>
#include<iostream>
using namespace std;
string ch;
string ch2;
int main(){
int n;
while(scanf("%d",&n)==1)
{
int t=n-1;
cin>>ch;
ch2=ch;
reverse(ch2.begin(),ch2.end());//将数组倒置
int count=0; //计算倒置后与原数组最后的序列相同的个数
int max=0;
for(int i=0;i<n;i++){
if(ch2[count]==ch[i]) count++;
else {
count=0;
if(ch2[count]==ch[i])i--;
}
if(max<count&&(i==n-1))max=count;//当且仅当此序列位于原数组的最后
}
max=n-max;
printf("%d\n",max);
for(int i=0;i<n;i++)
printf("%c",ch[i]);
for(int i=max-1;i>=0;i--)
printf("%c",ch[i]);
printf("\n");
}
return 0;
}