Print all palindrome permutations of a string in C++

C++Server Side ProgrammingProgramming

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
raja
Published on 16-Jan-2020 17:33:47
Advertisements