Lexicographically largest string possible consisting of at most K consecutive similar characters | Function to return nearest lower character ; Traverse charset from start - 1 ; If no character can be appended ; Function to find largest string ; Stores the frequency of characters ; Traverse the 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 ; Driver code ; Given string s
def nextAvailableChar ( charset , start ) : NEW_LINE INDENT for i in range ( start - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( charset [ i ] > 0 ) : NEW_LINE INDENT charset [ i ] -= 1 NEW_LINE return chr ( i + ord ( ' a ' ) ) NEW_LINE DEDENT DEDENT return ' \0' NEW_LINE DEDENT def newString ( originalLabel , limit ) : NEW_LINE INDENT n = len ( originalLabel ) NEW_LINE charset = [ 0 ] * ( 26 ) NEW_LINE newStrings = " " NEW_LINE for i in originalLabel : NEW_LINE INDENT charset [ ord ( i ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 25 , - 1 , - 1 ) : NEW_LINE INDENT count = 0 NEW_LINE while ( charset [ i ] > 0 ) : NEW_LINE INDENT newStrings += chr ( i + ord ( ' a ' ) ) NEW_LINE charset [ i ] -= 1 NEW_LINE count += 1 NEW_LINE if ( charset [ i ] > 0 and count == limit ) : NEW_LINE INDENT next = nextAvailableChar ( charset , i ) NEW_LINE if ( next == ' \0' ) : NEW_LINE INDENT return newStrings NEW_LINE DEDENT newStrings += next NEW_LINE count = 0 NEW_LINE DEDENT DEDENT DEDENT return newStrings NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " ccbbb " NEW_LINE K = 2 NEW_LINE print ( newString ( S , K ) ) NEW_LINE DEDENT