给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。
若可行,输出任意可行的结果。若不可行,返回空字符串。
示例 1:
输入: S = “aab”
输出: “aba”
示例 2:
输入: S = “aaab”
输出: “”
注意:
S 只包含小写字母并且长度在[1, 500]区间内。
思路:
首先,判断是否可以重构字符串,若某个字符出现的频率大于字符串长度的一半,就不能重构。
难点在于如何重构字符串使任意相同字符不重复。网上看到别人做法,构造一个类用于存放字符和字符出现的频率,然后用优先队列来解决。
public String reorganizeString(String S) {
int len = S.length();
int[] data = new int[26];
for(int i=0;i<=len;i++) {
data[S.charAt(i)-'a']++;
}
PriorityQueue<NewChar> pq = new PriorityQueue<NewChar>(new Comparator<NewChar>() {
@Override
public int compare(NewChar o1, NewChar o2) {
return o2.count-o1.count;
}
}) ;
for(int i=0;i<26;i++) {
if(data[i]>0&&data[i]<=(len+1)/2)
pq.add(new NewChar(data[i],(char)(i+'a')));
else if(data[i]>(len+1)/2)
return "";
}
String str="";
while(pq.size()>1) {
NewChar c1 = pq.poll();
NewChar c2 = pq.poll();
if(str.length()==0 || c1.letter!=str.charAt(str.length()-1)) {
str += c1.letter;
str += c2.letter;
}
if(--c1.count>0) pq.add(c1);
if(--c2.count>0) pq.add(c2);
}
if(pq.size()>0)
str += pq.poll().letter;
return str;
}
class NewChar{
public int count;
public char letter;
public NewChar(int count,char letter) {
this.count = count;
this.letter = letter;
}