CodeForces - 505A B - Mr. Kitayuta's Gift

本文介绍了一种通过插入一个字符使给定字符串变为回文串的算法。通过删除指定字符判断剩余部分是否为回文,若是,则在相应位置插入字符完成回文构造。提供了C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A. Mr. Kitayuta's Gift
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Mr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly one lowercase English letter into s to make it a palindrome. A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" and "kitayuta" are not.

You can choose any lowercase English letter, and insert it to any position of s, possibly to the beginning or the end of s. You have to insert a letter even if the given string is already a palindrome.

If it is possible to insert one lowercase English letter into s so that the resulting string will be a palindrome, print the string after the insertion. Otherwise, print "NA" (without quotes, case-sensitive). In case there is more than one palindrome that can be obtained, you are allowed to print any of them.

Input
The only line of the input contains a string s (1 ≤ |s| ≤ 10). Each character in s is a lowercase English letter.

Output
If it is possible to turn s into a palindrome by inserting one lowercase English letter, print the resulting string in a single line. Otherwise, print "NA" (without quotes, case-sensitive). In case there is more than one solution, any of them will be accepted.

Examples
input
revive
output
reviver
input
ee
output
eye
input
kitayuta
output
NA
Note
For the first sample, insert 'r' to the end of "revive" to obtain a palindrome "reviver".

For the second sample, there is more than one solution. For example, "eve" will also be accepted.

For the third sample, it is not possible to turn "kitayuta" into a palindrome by just inserting one letter.


这道题题意是在字符串中间必须要加入一个字符,使得整个字符串成为回文。如果无论如何在哪里插入字符串都无法构成回文的话 就输出NA 能插入就输出字符串


其实这道题我们仔细想想就会发现 从后往前想 如果这个字符串是个回文串的话 我们删去一个字符 成为一个新串 那么我们在这个新串的另一处再把刚才删除的第一个字符的位置相对的字符再删除的话 就会再度成为回文 所以我们不妨尝试每一个字符 如果删去之后还是个回文串 那么我们就再此字符的相对位置再加一个字符

当然暴力也可以 枚举每一个位置和每一个字符 如果构成回文就插入


#include<bits/stdc++.h>
using namespace std;
int main()
{
	string a;
	cin>>a;
	bool flag=1;
	for(int i=0;i<a.length();i++)
	{
		flag=1;
		for(int j=0,p=a.length()-1;j<a.length()&&p>=0;j++,p--)
		{
			if(j==i)j++;
			if(p==i)p--;//1
			if(a[p]!=a[j]){
				flag=0;
				break;
			}
		}
		if(flag){
			int tem=i;
			if(tem+1<=a.length()/2)
				a.insert(a.end()-tem,a[i]);
			else 
				a.insert(a.begin()+(a.length()-1-tem),a[i]);
				break;
		}
	}
	
	if(flag)cout<<a<<endl;
	else cout<<"NA"<<endl;	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值