Lexicographically largest string possible consisting of at most K consecutive similar characters | Java solution for above approach ; Function to find largest string ; Stores the frequency of characters ; Traverse the string ; Stores the resultant string ; Append larger character ; Decrease count in charset ; Increase count ; Check if count reached to charLimit ; Find nearest lower char ; If no character can be appended ; Append nearest lower character ; Reset count for next calculation ; Return new largest string ; Function to return nearest lower character ; Traverse charset from start - 1 ; If no character can be appended ; Driver Code
import java . util . * ; class GFG { static String newString ( String originalLabel , int limit ) { int n = originalLabel . length ( ) ; int [ ] charset = new int [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { charset [ originalLabel . charAt ( i ) - ' a ' ] ++ ; } StringBuilder newString = new StringBuilder ( n ) ; for ( int i = 25 ; i >= 0 ; i -- ) { int count = 0 ; while ( charset [ i ] > 0 ) { newString . append ( ( char ) ( i + ' a ' ) ) ; charset [ i ] -- ; count ++ ; if ( charset [ i ] > 0 && count == limit ) { Character next = nextAvailableChar ( charset , i ) ; if ( next == null ) return newString . toString ( ) ; newString . append ( next ) ; count = 0 ; } } } return newString . toString ( ) ; } static Character nextAvailableChar ( int [ ] charset , int start ) { for ( int i = start - 1 ; i >= 0 ; i -- ) { if ( charset [ i ] > 0 ) { charset [ i ] -- ; return ( char ) ( i + ' a ' ) ; } } return null ; } public static void main ( String [ ] args ) { String S = " ccbbb " ; int K = 2 ; System . out . println ( newString ( S , K ) ) ; } }