767. 重构字符串
给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。
若可行,输出任意可行的结果。若不可行,返回空字符串。
示例 1:
输入: S = “aab”
输出: “aba”
示例 2:
输入: S = “aaab”
输出: “”
注意:
S 只包含小写字母并且长度在[1, 500]区间内。
class Solution {
public String reorganizeString(String S) {
if (S == null || S.length() == 0) {
return "";
}
int length = S.length();
int[] counts = new int[26];
for (char c : S.toCharArray()) {
counts[c - 'a'] += 100;
}
for (int i = 0; i < 26; ++i) {
counts[i] += i;
}
Arrays.sort(counts);
char[] result = new char[length];
int t = 1;
for (int code : counts) {
int ct = code / 100;
char ch = (char) ('a' + (code % 100));
if (ct > (length + 1) / 2) {
return "";
}
for (int i = 0; i < ct; ++i) {
if (t >= length) {
t = 0;
}
result[t] = ch;
t += 2;
}
}
return String.valueOf(result);
}
}