File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
2182-construct-string-with-repeat-limit Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public String repeatLimitedString (String s , int repeatLimit ) {
3+ int [] freq = new int [26 ];
4+ for (char ch : s .toCharArray ()){
5+ freq [ch -'a' ]++;
6+ }
7+ StringBuilder op = new StringBuilder ();
8+ int prev =-1 ;
9+ for (int i =25 ;i >=0 ;i --){
10+
11+ if (op .length ()>=s .length ()){
12+ break ;
13+ }
14+ if (freq [i ]==0 ) continue ;
15+
16+ if (op .length ()>0 && op .charAt (op .length ()-1 )!=(char )('a' + i ) && prev !=-1 ){
17+ op .append ((char )('a' + i ));
18+ freq [i ]--;
19+
20+ i =prev ;
21+ }
22+
23+ if (freq [i ]<=repeatLimit ){
24+ op .append (genrate (freq [i ],(char )('a' + i )));
25+ freq [i ]=0 ;
26+ prev =-1 ;
27+ }
28+ else if (freq [i ]>repeatLimit ){
29+ freq [i ]-=repeatLimit ;
30+ op .append (genrate (repeatLimit ,(char )('a' + i )));
31+
32+ prev =i ;
33+ }
34+ }
35+ return op .toString ();
36+ }
37+ public String genrate (int k ,char c ){
38+ String key ="" ;
39+ while (k -->0 ){
40+ key +=c ;
41+ }
42+ return key ;
43+ }
44+ }
You can’t perform that action at this time.
0 commit comments