
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find String After Adding Character to Become Non-Palindrome in C++
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
Advertisements