Count of unique palindromic strings of length X from given string | C ++ implementation to count different palindromic string of length X from the given string S ; Function to count different palindromic string of length X from the given string S ; Base case ; Create the frequency array ; Intitalise frequency array with 0 ; Count the frequency in the string ; Store frequency of the char ; check the frequency which is greater than zero ; No . of different char we can put at the position of the i and x - i ; Iterator pointing to the last element of the set ; decrease the value of the char we put on the position i and n - i ; different no of char we can put at the position x / 2 ; Return total no of different string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long findways ( string s , int x ) { if ( x > ( int ) s . length ( ) ) return 0 ; long long int n = ( int ) s . length ( ) ; int freq [ 26 ] ; memset ( freq , 0 , sizeof freq ) ; for ( int i = 0 ; i < n ; ++ i ) freq [ s [ i ] - ' a ' ] ++ ; multiset < int > se ; for ( int i = 0 ; i < 26 ; ++ i ) if ( freq [ i ] > 0 ) se . insert ( freq [ i ] ) ; long long ans = 1 ; for ( int i = 0 ; i < x / 2 ; ++ i ) { long long int count = 0 ; for ( auto u : se ) { if ( u >= 2 ) count ++ ; } if ( count == 0 ) return 0 ; else ans = ans * count ; auto p = se . end ( ) ; p -- ; int val = * p ; se . erase ( p ) ; if ( val > 2 ) se . insert ( val - 2 ) ; } if ( x % 2 != 0 ) { long long int count = 0 ; for ( auto u : se ) if ( u > 0 ) count ++ ; ans = ans * count ; } return ans ; } int main ( ) { string s = " aaa " ; int x = 2 ; cout << findways ( s , x ) ; return 0 ; }