Number of palindromic permutations | Set 1 | PHP 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
< ? php $ MAX = 256 ; function fact ( $ n ) { $ res = 1 ; for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) $ res = $ res * $ i ; return $ res ; } function countPalinPermutations ( & $ str ) { global $ MAX ; $ n = strlen ( $ str ) ; $ freq = ( 0 ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ res = fact ( $ n / 2 ) ; $ oddFreq = false ; for ( $ i = 0 ; $ i < $ MAX ; $ i ++ ) { $ half = $ freq [ $ i ] / 2 ; if ( $ freq [ $ i ] % 2 != 0 ) { if ( $ oddFreq == true ) return 0 ; $ oddFreq = true ; } $ res = $ res / fact ( $ half ) ; } return $ res ; } $ str = " gffg " ; echo countPalinPermutations ( $ str ) ; ? >