C++程序查找string在添加字符'a'后使得string为非回文串
假设我们有一个字符串S,其中包含小写英文字母。我们必须在一个字符'a'中插入S。在插入之后,如果我们可以使S不是回文,则返回该字符串,否则返回“impossible”。
因此,如果输入类似于S =“bpapb”,那么输出将为“bpaapb”。
步骤
要解决这个问题,我们将遵循以下步骤-
if concatenation of S and "a" is not palindrome, then: return S concatenation 'a' otherwise when concatenation of "a" + S is not palindrome, then: return 'a' concatenation S Otherwise return "Impossible"
示例
让我们看看以下实现以获得更好的理解 -
#include <bits/stdc++.h>
using namespace std;
bool p(const string& s) {
for (int i = 0; i < s.size() / 2; i++)
if (s[i] != s[s.size() - 1 - i])
return false;
return true;
}
string solve(string S) {
if (!p(S + 'a'))
return S + 'a';
else if (!p('a' + S))
return 'a' + S;
else
return "Impossible";
}
int main() {
string S = "bpapb";
cout << solve(S) << endl;
}输入
"bpapb"
输出
bpapba
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP