-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorderString.java
More file actions
42 lines (36 loc) · 1.1 KB
/
Copy pathReorderString.java
File metadata and controls
42 lines (36 loc) · 1.1 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
package LeetcodePractice;
public class ReorderString {
public static String sortString(String s) {
int[] freq = new int[26];
for (char c : s.toCharArray()) {
freq[c - 'a']++;
}
StringBuilder result = new StringBuilder();
int remaining = s.length();
while (remaining > 0) {
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
result.append((char) (i + 'a'));
freq[i]--;
remaining--;
}
}
for (int i = 25; i >= 0; i--) {
if (freq[i] > 0) {
result.append((char) (i + 'a'));
freq[i]--;
remaining--;
}
}
}
return result.toString();
}
public static void main(String[] args) {
String s1 = "aaaabbbbcccc";
String s2 = "rat";
String s3 = "leetcode";
System.out.println(sortString(s1));
System.out.println(sortString(s2));
System.out.println(sortString(s3));
}
}