Check if string can be rearranged so that every Odd length Substring is Palindrome | Java implementation of the approach ; Function to check is it possible to rearrange the string such that every odd length substring is palindrome ; Length of the string ; To count number of distinct character in string ; To count frequency of each character ; Inserting into set ; Incrementing the frequency ; All characters in the string are same ; There are more than 2 different character in string ; Currently there is 2 different character in string ; Get the frequencies of the characters that present in string ; Difference between their count is less than or equal to 1 ; Driver Code
import java . util . * ; class GFG { static boolean IsPossible ( String s ) { int n = s . length ( ) ; HashSet < Character > count = new HashSet < > ( ) ; HashMap < Character , Integer > map = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { count . add ( s . charAt ( i ) ) ; map . put ( s . charAt ( i ) , map . get ( s . charAt ( i ) ) == null ? 1 : map . get ( s . charAt ( i ) ) + 1 ) ; } if ( count . size ( ) == 1 ) return true ; if ( count . size ( ) > 2 ) return false ; String newString = count . toArray ( ) . toString ( ) ; int j = 0 ; char it = newString . charAt ( j ) ; int x = 0 , y = 0 ; x = map . get ( it ) == null ? 0 : map . get ( it ) ; j ++ ; it = newString . charAt ( j ) ; y = map . get ( it ) == null ? 0 : map . get ( it ) ; if ( Math . abs ( x - y ) <= 1 ) return true ; return false ; } public static void main ( String [ ] args ) { String s = " aaaddad " ; if ( IsPossible ( s ) ) System . out . println ( " YES " ) ; else System . out . println ( " NO " ) ; } }