Print all palindrome permutations of a string in C++



In this problem, we are given a string and we have to print all the palindromic permutations that are possible from the characters of that string.

Let’s take an example to understand the problem βˆ’

Input βˆ’ string = β€˜aabb’

Output βˆ’ abba baab

To solve this problem we have to take the characters of the string and one by one generate all palindrome strings using these characters.

Step 1 βˆ’ Check if the string is a palindrome or not, print β€˜Not Possible’ if not.

Step 2 βˆ’ If it can make palindrome, then make it into half and lexicographically select each letter of string.

Step 3 βˆ’ Traverse through the permutations created and reverse the half side for even length string and for odd frequency, the odd character should be in-mid to create a palindrome.

Step 4 βˆ’ print all the palindrome created.

Program to implement the algorithm βˆ’

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
#define M 26
bool isPalindrome(string str, int* freq){
   memset(freq, 0, M * sizeof(int));
   int l = str.length();
   for (int i = 0; i < l; i++)
      freq[str[i] - 'a']++;
   int odd = 0;
   for (int i = 0; i < M; i++)
      if (freq[i] % 2 == 1)
   odd++;
   if ((l % 2 == 1 && odd == 1 ) || (l %2 == 0 && odd == 0))
      return true;
   else
      return false;
}
string reverse(string str){
   string rev = str;
   reverse(rev.begin(), rev.end());
   return rev;
}
void generatePalindromePermutation(string str){
   int freq[M];
   if (!isPalindrome(str, freq))
   return;
   int l = str.length();
   string half ="";
   char oddC;
   for (int i = 0; i < M; i++) {
      if(freq[i] % 2 == 1)
      oddC = i + 'a';
      half += string(freq[i] / 2, i + 'a');
   }
   string palindrome;
   do {
      palindrome = half;
      if (l % 2 == 1)
         palindrome += oddC;
      palindrome += reverse(half);
      cout<<palindrome<<endl;
   }
   while (next_permutation(half.begin(), half.end()));
}
int main() {
   string str="abab";
   cout<<"All palindrome permutations of "<<str<<" are :\n";
   generatePalindromePermutation(str);
   return 0;
}

Output

All palindrome permutations of abab are :
abba
baab
Updated on: 2020-07-14T07:34:45+05:30

389 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements