public String rearange(String str) {
if (str == null || str.isEmpty()) {
return str;
}
HashMap<Character, Integer> cnt = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char cur = str.charAt(i);
if (cnt.containsKey(cur)) {
cnt.put(cur, cnt.get(cur) + 1);
} else {
cnt.put(cur, 1);
}
}
PriorityQueue<RevFreqNode> queue = new PriorityQueue<>(10, new Comparator<RevFreqNode>() {
public int compare(RevFreqNode n1, RevFreqNode n2) {
return n2.freq - n1.freq;
}
});
for (Map.Entry<Character, Integer> entry : cnt.entrySet()) {
queue.offer(new RevFreqNode(entry.getKey(), entry.getValue()));
}
RevFreqNode last = null;
StringBuilder sb = new StringBuilder();
while (!queue.isEmpty()) {
RevFreqNode cur = queue.poll();
sb.append(cur.val);
cur.freq = cur.freq - 1;
if (last != null && last.freq > 0) {
queue.offer(last);
}
last = cur;
}
if (sb.length() != str.length()) {
return "Not Possible";
}
return sb.toString();
}
public static void main(String[] args) {
UberPhoneSnapOnsiteRearrangeChar sol = new UberPhoneSnapOnsiteRearrangeChar();
String str1 = "aaabc";
String str2 = "aaabb";
String str3 = "aa";
String str4 = "aaaabc";
System.out.println(sol.rearange(str1));
System.out.println(sol.rearange(str2));
System.out.println(sol.rearange(str3));
System.out.println(sol.rearange(str4));
}
class RevFreqNode {
Character val;
int freq;
public RevFreqNode(char v, int f) {
val = v;
freq = f;
}
}