问题描述
“回文串”是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串。给你一个字符串,问最少在字符串尾添加多少字符,可以使得字符串变为回文串。
输入格式
有多组测试数据。
每组测试数据第一行是一个正整数N,表示字符串长度,接下来一行是长度为N的字符串,字符串中只有小写字母。
N=0表示输入结束,并且不需要处理。
40%的数列元素个数N 1 ≤ N≤ 100;
30%的数列元素个数N 1 ≤ N≤ 1000;
20%的数列元素个数N 1 ≤ N≤ 10000;
10%的数列元素个数N 1 ≤ N≤ 100000;
输出格式
对于每组测试数据,输出一个非负整数:添加最少的字符数,可以使得字符串变为回文串。
样例输入
3
aba
4
aaac
0
样例输出
0
3
#include<iostream>
#include<string>
using namespace std;
bool pan(string s){
unsigned int count=0;
unsigned int num=s.length();
if(num%2==1){
for(unsigned int i=0;i<(num-1)/2;i++){
if(s[i]==s[num-i-1])
count++;
}
if(count==(num-1)/2)
return true;
else
return false;
}
else{
for(unsigned int i=0;i<num/2;i++){
if(s[i]==s[num-i-1])
count++;
}
if(count==num/2)
return true;
else
return false;
}
}
int main(){
int temp;
string str;
int res;
while(cin>>temp and temp!=0){
res=0;
cin>>str;
if(pan(str))
res=0;
else{
for(int i=0;i<temp;i++){
string copy;
copy.clear();
for(int j=i;j>=0;j--){
copy+=str[j];
}
copy=str+copy;
if(pan(copy)){
res=i+1;
break;
}
}
}
cout<<res<<endl;
}
return 0;
}