面试题:给定一个字符串,问是否能通过添加一个字母将其变为回文串

题目描述

给定一个字符串,问是否能通过添加一个字母将其变为回文串。

输入描述:
一行一个由小写字母构成的字符串,字符串长度小于等于10

 

输出描述:
输出答案(YES\NO).

 

输入例子:
coco

 

输出例子:

YES

题目不严谨,没说明是否可以在字符串中间插入,如果只是在首尾添加,我的方法是对的

#include<iostream>
#include<iomanip>
#include<math.h>
#include <vector>
#include <string.h>
using namespace std;
bool isBackString(string str)
{
	int length = str.length();
	char* a = new char[length+1];
	strcpy(a,str.c_str());
	int start = 0;
	int end = length - 1;
	while (start<end)
	{
		if (a[start] != a[end])
			return false;
		start++;
		end--;
	}
	return true;
}
int main()
{
	string str;
	while (cin >> str)
	{
		char cbegin = str[0];
		char cend = str[str.length() - 1];
		if (isBackString(str+cbegin))
		{
			cout << "YES" << endl;
		}else if (isBackString(cend+str))
		{
			cout << "YES" << endl;
		}
		else
		{
			cout << "NO" << endl;
		}
	}

	//system("pause");
	return 0;
}
附上别人的代码,思路是通过删除字符,判断是不是回文,这个方法才是对的,
另外判断是否是回文可以直接用用reverse函数,我不知道有这个函数。。
其实如果直接反转字符串,再比较也是可以的
#include <iostream>
#include <cstdlib>
#include <string>
#include <algorithm>

using namespace std;

/*判断是否为回文串*/
bool isPalindrome(const string &str)
{
	string s = str;
	reverse(s.begin(), s.end());
	return s == str;
}

int main()
{
	string str;
	while (cin >> str)
	{
		if (str.empty() || str.length() == 1)
			cout << "YES";
		else
		{
			int len = str.length();
			string tmp;
			bool ret = false;
			for (int i = 0; i < len; ++i)
			{
				tmp = str.substr(0, i) + str.substr(i + 1);
				if (isPalindrome(tmp))
				{
					ret = true;
					break;
				}//
			}
			if (ret)
				cout << "YES" << endl;
			else
				cout << "NO" << endl;
		}
	}//while

	return 0;
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值