Problem
Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
If possible, output any possible result. If not possible, return the empty string.
Example 1:
Input: S = “aab”Output: “aba”Example 2:
Input: S = “aaab”Output: “”Note:
S will consist of lowercase letters and have length in range [1, 500].
Solution
class Solution {
public String reorganizeString(String S) {
int n = S.length();
int[] cnt = new int[128];
char mc = ‘a’;
for (char c : S.toCharArray()) {
cnt++;
mc = (cnt > cnt[mc]) ? c : mc;
}
if (cnt[mc] == 1) {
return S;
}
if (cnt[mc] > (n+1)/2) {
return “”;
}
StringBuilder[] sb = new StringBuilder[cnt[mc]];
for (int i = 0; i < sb.length; i ++) {
sb[i] = new StringBuilder();
sb[i].append(mc);
}
int k = 0;
for (char c = ‘a’; c <= ‘z’; c++) {
while (c != mc && cnt > 0) {
sb[k++].append(c);
cnt–;
k %= sb.length;
}
}
for (int i = 1; i < sb.length; i++) {
sb[0].append(sb[i]);
}
return sb[0].toString();
}
}