思路:
贪心+大顶堆
1.统计每个字符出现次数,找到最多出现此处若大于(len+1)/2,则直接返回空。
2.按照出现次数直接建立大顶堆。
3.每次从大顶堆取两个字符,加入StringBuffer,以此类推。
4.若队列剩下最后一个元素,则直接加入,否则返回
参考:官方解法一
public String reorganizeString(String S) {
if (S.length() < 2) {
return S;
}
int[] a = new int[26];
int len = S.length();
int maxCount = 0;
for (int i = 0; i < len; i++) {
char c = S.charAt(i);
a[c-'a']++;
maxCount = Math.max(maxCount,a[c-'a']);
}
if(maxCount > (len+1)/2){
return "";
}
PriorityQueue<Character> priorityQueue = new PriorityQueue<>(new Comparator<Character>() {
@Override
public int compare(Character o1, Character o2) {
return a[o2-'a']-a[o1-'a'];
}
});
int count = 0;
for (int i = 0; i < 26; i++) {
if(a[i] > 0){
priorityQueue.offer((char)(i+'a'));
}
}
StringBuffer sb = new StringBuffer();
while (priorityQueue.size() > 1){
char c1 = priorityQueue.poll();
char c2 = priorityQueue.poll();
sb.append(c1);
sb.append(c2);
a[c1-'a']--;
a[c2-'a']--;
if(a[c1-'a'] > 0){
priorityQueue.offer(c1);
}
if(a[c2-'a'] > 0){
priorityQueue.offer(c2);
}
}
if(!priorityQueue.isEmpty()){
sb.append(priorityQueue.poll());
}
return sb.toString();
}