题干
给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。
若可行,输出任意可行的结果。若不可行,返回空字符串。
示例 1:
输入: S = "aab"
输出: "aba"
示例 2:
输入: S = "aaab"
输出: ""
注意:
S 只包含小写字母并且长度在[1, 500]区间内。
想法
由于考研 十二月的每日一题就暂时不做了哈
今天 这道题,首先如果有一个字母出现次数达到了(字符串长度+1)/2,那就一定不能形成。。
然后使用大根队来维护出现次数最多的元素。
每次取出大根队里最顶端的两个,交替形成字符串,如果取出后,字符出现次数仍不为0,那就把它放回去,如此反复直到只剩一个元素,或者没有。
Java代码
class Solution {
public String reorganizeString(String S) {
int []count=new int[26];
int maxamount=Integer.MIN_VALUE;
int len=S.length();
for (int i = 0; i < len; i++) {
count[S.charAt(i)-'a']++;
maxamount=Math.max(maxamount,count[S.charAt(i)-'a']);
}
if(maxamount>(len+1)/2){
return "";
}
PriorityQueue <Character>heap=new PriorityQueue(new Comparator<Character>() {
@Override
public int compare(Character c1, Character c2) {
return count[c2-'a']-count[c1-'a'];
}
});
for (char c='a';c<='z';c++){
if(count[c-'a']>0){
heap.offer(c);
}
}
StringBuffer sb=new StringBuffer();
while (heap.size()>1){
char char1=heap.poll();
char char2=heap.poll();
sb.append(char1);
sb.append(char2);
int index1=char1-'a',index2=char2-'a';
count[index1]--;
count[index2]--;
if(count[index1]>0){
heap.offer(char1);
}
if(count[index2]>0){
heap.offer(char2);
}
}
if(heap.size()>0){
sb.append(heap.poll());
}
return sb.toString();
}
}