Count of unique palindromic strings of length X from given string | Java 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
import java . util . Arrays ; import java . util . HashSet ; import java . util . Set ; class GFG { static int findways ( String s , int x ) { if ( x > s . length ( ) ) return 0 ; int n = s . length ( ) ; int [ ] freq = new int [ 26 ] ; Arrays . fill ( freq , 0 ) ; for ( int i = 0 ; i < n ; ++ i ) freq [ s . charAt ( i ) - ' a ' ] ++ ; multiset < int > se ; Set < Integer > se = new HashSet < > ( ) ; for ( int i = 0 ; i < 26 ; ++ i ) if ( freq [ i ] > 0 ) se . add ( freq [ i ] ) ; int ans = 1 ; for ( int i = 0 ; i < x / 2 ; ++ i ) { int count = 0 ; for ( int u : se ) { if ( u >= 2 ) count ++ ; } if ( count == 0 ) return 0 ; else ans = ans * count ; int p = ( int ) se . toArray ( ) [ se . size ( ) - 1 ] ; int val = p ; se . remove ( p ) ; if ( val > 2 ) se . add ( val - 2 ) ; } if ( x % 2 != 0 ) { int count = 0 ; for ( int u : se ) if ( u > 0 ) count ++ ; ans = ans * count ; } return ans ; } public static void main ( String [ ] args ) { String s = " aaa " ; int x = 2 ; System . out . println ( findways ( s , x ) ) ; } }