Rearrange string such that no pair of adjacent characters are of the same type | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string rearrange ( string s ) { string s1 = " " , s2 = " " ; for ( char x : s ) { isalpha ( x ) ? s1 . push_back ( x ) : s2 . push_back ( x ) ; } int n = s1 . size ( ) ; int m = s2 . size ( ) ; if ( abs ( n - m ) > 1 ) return " - 1" ; int i = 0 , j = 0 , k = 0 ; int flag = ( n >= m ) ? 1 : 0 ; while ( i < n and j < m ) { if ( flag ) s [ k ++ ] = s1 [ i ++ ] ; else s [ k ++ ] = s2 [ j ++ ] ; flag = ! flag ; } return s ; } int main ( ) { string str = " geeks2020" ; cout << rearrange ( str ) << endl ; return 0 ; }