-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
42 lines (42 loc) · 1.05 KB
/
Solution.java
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
class Solution {
public String reorganizeString(String s) {
int[] cnt = new int[26];
int mx = 0;
for (char c : s.toCharArray()) {
int t = c - 'a';
++cnt[t];
mx = Math.max(mx, cnt[t]);
}
int n = s.length();
if (mx > (n + 1) / 2) {
return "";
}
int k = 0;
for (int v : cnt) {
if (v > 0) {
++k;
}
}
int[][] m = new int[k][2];
k = 0;
for (int i = 0; i < 26; ++i) {
if (cnt[i] > 0) {
m[k++] = new int[] {cnt[i], i};
}
}
Arrays.sort(m, (a, b) -> b[0] - a[0]);
k = 0;
StringBuilder ans = new StringBuilder(s);
for (int[] e : m) {
int v = e[0], i = e[1];
while (v-- > 0) {
ans.setCharAt(k, (char) ('a' + i));
k += 2;
if (k >= n) {
k = 1;
}
}
}
return ans.toString();
}
}