1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// @Title: 构造限制重复的字符串 (Construct String With Repeat Limit)
// @Author: 15816537946@163.com
// @Date: 2022-02-20 13:38:03
// @Runtime: 30 ms
// @Memory: 42.3 MB
class Solution {
    public String repeatLimitedString(String s, int repeatLimit) {
        int count[]=new int[26];
        for(int i=0;i<s.length();i++){count[s.charAt(i)-'a']++;}
        StringBuilder ans=new StringBuilder();
        int c=0;
        int i=25;
        while(true){        
            while(i>=0&&count[i]==0){i--;}
            if(i==-1){break;}
            while(count[i]>0&&c<repeatLimit){
                c++;
                ans.append((char)(i+'a'));
                count[i]--;
            }
            c=0;
            if(count[i]==0){continue;}
            else{
                int j=i-1;
            while(j>=0&&count[j]==0){j--;}
            if(j>=0){
                ans.append((char)(j+'a'));
                count[j]--;
            }
            else{break;}
            }
            
        }
        return ans.toString();
    }
}