C++ program to find string after adding character 'a' string becomes non-palindrome


Suppose we have a string S with lowercase English letters. We must insert exactly one character 'a' in S. After inserting that if we can make S not a palindrome then return that string, otherwise return "impossible".

So, if the input is like S = "bpapb", then the output will be "bpaapb"

Steps

To solve this, we will follow these steps −

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"

Example

Let us see the following implementation to get better understanding −

#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;
}

Input

"bpapb"

Output

bpapba

Updated on: 03-Mar-2022

79 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements