You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more thanrepeatLimit times in a row. You do not have to
use all characters from s.
Return _the lexicographically largest _repeatLimitedStringpossible.
A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.
Input: s ="cczazcc", repeatLimit =3Output: "zzcccac"Explanation: We use all of the characters from s to construct the repeatLimitedString "zzcccac".The letter 'a' appears at most 1 time in a row.The letter 'c' appears at most 3 times in a row.The letter 'z' appears at most 2 times in a row.Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.The string is the lexicographically largest repeatLimitedString possible so we return"zzcccac".Note that the string "zzcccca"is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString.
Example 2:
1
2
3
4
5
6
7
8
Input: s ="aababab", repeatLimit =2Output: "bbabaa"Explanation: We use only some of the characters from s to construct the repeatLimitedString "bbabaa".The letter 'a' appears at most 2 times in a row.The letter 'b' appears at most 2 times in a row.Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.The string is the lexicographically largest repeatLimitedString possible so we return"bbabaa".Note that the string "bbabaaa"is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString.
To maximize the lexicographical order, we append the characters in sorted order starting from the largest character.
We keep track of the number of consecutive additions of the current character and switch characters when we reach the specified repeatLimit.
Here is the approach:
Count the frequency of each character.
Sort the characters in descending order.
Append characters to the result string while ensuring no character exceeds the repeatLimit. If the limit is reached, insert a smaller character to break the sequence.