题目描述
给定一个字符串,问是否能通过添加一个字母将其变为回文串。
输入描述:
一行一个由小写字母构成的字符串,字符串长度小于等于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;
}