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);
}
}