-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC2182.java
More file actions
64 lines (50 loc) · 1.6 KB
/
LC2182.java
File metadata and controls
64 lines (50 loc) · 1.6 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* LC2182
*/
import java.util.Scanner;
import java.lang.StringBuilder;
public class LC2182 {
public static String repeatLimitedString(String s, int repeatLimit) {
int[] freq = new int[26];
for (char ch : s.toCharArray()) {
freq[ch - 'a']++;
}
StringBuilder sb = new StringBuilder();
int index = 25; // Start from the largest character
while (index >= 0) {
if (freq[index] == 0) {
index--;
continue;
}
int used = Math.min(freq[index], repeatLimit);
for (int i = 0; i < used; i++) {
sb.append((char) ('a' + index));
}
freq[index] -= used;
if (freq[index] > 0) { // find a smaller character
int prevIndex = index - 1;
while (prevIndex >= 0 && freq[prevIndex] == 0) {
prevIndex--;
}
if (prevIndex < 0) {
break;
}
sb.append((char) ('a' + prevIndex));
freq[prevIndex]--;
}
}
return sb.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter The String S : ");
String s = sc.nextLine();
System.out.println();
System.out.print("Enter The Repeat Limit : ");
int repeatLimit = sc.nextInt();
System.out.println();
String ans = repeatLimitedString(s, repeatLimit);
System.out.println(ans);
sc.close();
}
}