Medium
You are given:
s
consisting of lowercase English letters.repeatLimit
.Your task is to construct a new string repeatLimitedString
using the characters of s
, such that no letter appears more than repeatLimit
times consecutively.
The goal is to return the lexicographically largest string possible.
a
is larger than string b
if:
a
has a character later in the alphabet.Input:
s = "cczazcc"
repeatLimit = 3
Output:
"bbabaa"
Steps:
s
in descending order to maximize the lexicographical order:repeatLimit
times consecutively.'z'
→ appears 2 times.'c'
→ appears 3 times.'a'
→ appears 1 time.'c'
→ 1 time (to avoid breaking the repeatLimit
rule).'z'
appears at most 2 times consecutively.'c'
appears at most 3 times consecutively.'a'
appears only 1 time.The string "zzcccac"
satisfies all conditions and is lexicographically largest.
Input:
s = "aaabbccc" repeatLimit = 2
Output:
"ccbbaacc"
Loading component...
Loading component...
Main Function is not defined.
public static String repeatLimitedString(String s, int repeatLimit) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
StringBuilder result = new StringBuilder();
int freq =1
int pointer = chars.length -1;
for(int i = chars.length -1; i >= 0 ; i--){
if(result.length() > 0 && result.charAt(result.length() - 1) == chars[i]) {
if (freq < repeatLimit) {
result.append(chars[i]);
freq++;
}
else{
while ( pointer >= 0 && (chars[pointer] == chars[i] || pointer > i)) {
pointer--;
}
if(pointer >= 0) {
result.append(chars[pointer]);
char temp = chars[i];
chars[i] = chars[pointer];
chars[pointer] = temp;
freq =1 ;
}
else{
break;
}
}
}
else{
result.append(chars[i]);
freq =1;
}
}
return result.toString();
}//function end
Utility Function is not required.