Rearrange string such that no pair of adjacent characters are of the same type | Java program to implement the above approach ; Function to rearrange given alphanumeric String such that no two adjacent characters are of the same type ; Stores alphabets and digits ; Store the alphabets and digits separately in the Strings ; Stores the count of alphabets and digits ; If respective counts differ by 1 ; Desired arrangement not possible ; Stores the indexes ; Check if first character should be alphabet or digit ; Place alphabets and digits alternatively ; If current character needs to be alphabet ; If current character needs to be a digit ; Flip flag for alternate arrangement ; Return resultant String ; Driver Code ; Given String ; Function Call
class GFG { static String rearrange ( String s ) { String s1 = " " , s2 = " " , ans = " " ; char [ ] s3 = s . toCharArray ( ) ; for ( char x : s3 ) { if ( x >= ' a ' && x <= ' z ' ) s1 += x ; else s2 += x ; } int n = s1 . length ( ) ; int m = s2 . length ( ) ; if ( Math . abs ( n - m ) > 1 ) return " - 1" ; int i = 0 , j = 0 , k = 0 ; int flag = ( n >= m ) ? 1 : 0 ; while ( i < n && j < m ) { if ( flag != 0 ) ans += s1 . charAt ( i ++ ) ; else ans += s2 . charAt ( j ++ ) ; if ( flag == 1 ) flag = 0 ; else flag = 1 ; } return ans ; } public static void main ( String [ ] args ) { String str = " geeks2020" ; System . out . print ( rearrange ( str ) + "NEW_LINE"); } }