Check if a string can be split into two strings with same number of K | Java program for the above problem ; Function to print the arrangement of characters ; Stores frequency of characters ; Count the character having frequency K ; Count the character having frequency greater than K and not equal to 2 K ; Case 1 ; Case 2 ; Case 3 ; If all cases fail ; Driver code
import java . util . * ; class GFG { public static void DivideString ( String s , int n , int k ) { int i , c = 0 , no = 1 ; int c1 = 0 , c2 = 0 ; int [ ] fr = new int [ 26 ] ; char [ ] ans = new char [ n ] ; for ( i = 0 ; i < n ; i ++ ) { fr [ s . charAt ( i ) - ' a ' ] ++ ; } char ch = ' a ' , ch1 = ' a ' ; for ( i = 0 ; i < 26 ; i ++ ) { if ( fr [ i ] == k ) { c ++ ; } if ( fr [ i ] > k && fr [ i ] != 2 * k ) { c1 ++ ; ch = ( char ) ( i + ' a ' ) ; } if ( fr [ i ] == 2 * k ) { c2 ++ ; ch1 = ( char ) ( i + ' a ' ) ; } } for ( i = 0 ; i < n ; i ++ ) ans [ i ] = '1' ; HashMap < Character , Integer > mp = new HashMap < > ( ) ; if ( c % 2 == 0 c1 > 0 c2 > 0 ) { for ( i = 0 ; i < n ; i ++ ) { if ( fr [ s . charAt ( i ) - ' a ' ] == k ) { if ( mp . containsKey ( s . charAt ( i ) ) ) { ans [ i ] = '2' ; } else { if ( no <= ( c / 2 ) ) { ans [ i ] = '2' ; no ++ ; mp . replace ( s . charAt ( i ) , 1 ) ; } } } } if ( ( c % 2 == 1 ) && ( c1 > 0 ) ) { no = 1 ; for ( i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == ch && no <= k ) { ans [ i ] = '2' ; no ++ ; } } } if ( c % 2 == 1 && c1 == 0 ) { no = 1 ; int flag = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == ch1 && no <= k ) { ans [ i ] = '2' ; no ++ ; } if ( fr [ s . charAt ( i ) - ' a ' ] == k && flag == 0 && ans [ i ] == '1' ) { ans [ i ] = '2' ; flag = 1 ; } } } System . out . println ( ans ) ; } else { System . out . println ( " NO " ) ; } } public static void main ( String [ ] args ) { String S = " abbbccc " ; int N = S . length ( ) ; int K = 1 ; DivideString ( S , N , K ) ; } }