Number of palindromic permutations | Set 1 | Java program to find number of palindromic permutations of a given string ; Returns factorial of n ; Returns count of palindromic permutations of str . ; Count frequencies of all characters ; Since half of the characters decide count of palindromic permutations , we take ( n / 2 ) ! ; To make sure that there is at most one odd occurring char ; Traverse through all counts ; To make sure that the string can permute to form a palindrome ; If there are more than one odd occurring chars ; Divide all permutations with repeated characters ; Driver code
class GFG { static final int MAX = 256 ; static long fact ( int n ) { long res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } static int countPalinPermutations ( String str ) { int n = str . length ( ) ; int freq [ ] = new int [ MAX ] ; for ( int i = 0 ; i < n ; i ++ ) freq [ str . charAt ( i ) ] ++ ; long res = fact ( n / 2 ) ; boolean oddFreq = false ; for ( int i = 0 ; i < MAX ; i ++ ) { int half = freq [ i ] / 2 ; if ( freq [ i ] % 2 != 0 ) { if ( oddFreq == true ) return 0 ; oddFreq = true ; } res = res / fact ( half ) ; } return ( int ) res ; } public static void main ( String [ ] args ) { String str = " gffg " ; System . out . print ( countPalinPermutations ( str ) ) ; } }