Given a string, we need to print all possible palindromes that can be generated using letters of that string.
Input: str = "aabcb" Output: abcba bacab nput: str = "aabbcadad" Output: aabdcdbaa aadbcbdaa abadcdaba abdacadba adabcbada adbacabda baadcdaab badacadab bdaacaadb daabcbaad dabacabad dbaacaabd
Generation of palindrome can be done by following steps,
- First we need to check whether letters of string can make a palindrome or not, if not then return.
- After above checking we can make half part of first palindrome string (lexicographically smallest) by taking half frequency of each letter of the given string.
- Now traverse through all possible permutation of this half string and each time add reverse of this part at the end and add odd frequency character in mid between if string is of odd length, for making the palindrome.
Below is C++ implementation.
All palindrome permutations of aabbcadad aabdcdbaa aadbcbdaa abadcdaba abdacadba adabcbada adbacabda baadcdaab badacadab bdaacaadb daabcbaad dabacabad dbaacaabd
Let given string is "aabbcadad" Letters have following frequencies : a(4), b(2), c(1), d(2). As all letter has even frequency except one we can make palindromes with the letter of this string. Now half part is – aabd So traversing through all possible permutations of this half string and adding odd frequency character and reverse of string at the end we get following possible palindrome as final result : aabdcdbaa aadbcbdaa abadcdaba abdacadba adabcbada adbacabda baadcdaab badacadab bdaacaadb daabcbaad dabacabad dbaacaabd
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Print all permutations of a string in Java
- Print all distinct permutations of a given string with duplicates
- Write a program to print all permutations of a given string
- Java Program to print distinct permutations of a string
- Print all the palindromic permutations of given string in alphabetic order
- Minimum insertions to form a palindrome with permutations allowed
- Print all permutations with repetition of characters
- Print all permutations in sorted (lexicographic) order
- Iterative approach to print all permutations of an Array
- Print distinct sorted permutations with duplicates allowed in input
- Permutations of a given string using STL
- All permutations of a string using iteration
- Distinct permutations of the string | Set 2
- Time complexity of all permutations of a string
- Convert the string into palindrome string by changing only one character.