
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 Palindromic String B from Subsequence A in C++
Suppose we have a string A, we have to find another string B, that will be palindrome. And the given string A will be subsequence of B. The subsequence of a string is a string that can be formed by it by deleting some characters without changing the order of remaining characters. Suppose the string is “cotst”, then generated string will be “contest”. For the input of this program we have chosen A = “ab”, the generated string will be “abba”, this is palindrome.
To solve this, we will follow this approach. This is very simple, we will reverse the A, then append the reversed part after A, and form B. So B = A + reverse(A)
Example
#include<iostream> #include<algorithm> using namespace std; bool isPalindrome(string str) { string temp = str; reverse(str.begin(), str.end()); return str == temp; } string formPalindromeStr(string A) { string B = A; reverse(A.begin(), A.end()); A = A + B; if (isPalindrome(B)) return B; return A; } string reverse(string input) { string temp = input; int left, right = 0; right = temp.length() - 1; for (left = 0; left < right; left++, right--) swap(temp[left], temp[right]); return temp; } int main(int argc, char const *argv[]) { string A = "Hello"; cout << "The B is: " << formPalindromeStr(A); }
Output
The B is: olleHHello
Advertisements