面接問題:文字列を指定し、アルファベットを追加して文字列に変更できるかどうかを尋ねます.
2280 ワード
タイトルの説明
文字列を指定し、アルファベットを追加して文字列に変更できるかどうかを尋ねます.
説明を入力:
出力の説明:
入力例:
出力例:
YES
タイトルは厳密ではなく、文字列の真ん中に挿入できるかどうかは説明されていませんが、最初と最後に追加するだけであれば、私の方法は正しいです.
また、返信文が直接reverse関数を使うことができるかどうかを判断すると、この関数があるかどうか分かりません.
文字列を直接反転させて比較してもいいです
文字列を指定し、アルファベットを追加して文字列に変更できるかどうかを尋ねます.
説明を入力:
, 10。
出力の説明:
(YES\NO).
入力例:
coco
出力例:
YES
タイトルは厳密ではなく、文字列の真ん中に挿入できるかどうかは説明されていませんが、最初と最後に追加するだけであれば、私の方法は正しいです.
#include
#include
#include
#include
#include
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> 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
#include
#include
#include
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;
}