All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string""
.
s = "aabbcc", k = 3
Result: "abcabc"
The same letters are at least distance 3 from each other.
s = "aaabc", k = 3
Answer: ""
It is not possible to rearrange the string.
s = "aaadbbcc", k = 2
Answer: "abacabcd"
Another possible answer is: "abcabcda"
The same letters are at least distance 2 from each other.
class Solution {
public String rearrangeString(String s, int k) {
if (k <= 1) {
return s;
}
int[] count = new int[256];
for (char c : s.toCharArray()) {
++count[c];
}
PriorityQueue<CharInfo> maxHeap = new PriorityQueue<>();
for (int i = 0; i < 256; i++) {
if (count[i] != 0) {
maxHeap.add(new CharInfo((char)i, count[i]));
}
}
Queue<CharInfo> buffer = new LinkedList<>();
StringBuilder res = new StringBuilder();
while (!maxHeap.isEmpty()) {
CharInfo curChar = maxHeap.remove();
res.append(curChar.val);
--curChar.freq;
buffer.add(curChar);
if (buffer.size() == k) {
curChar = buffer.remove();
if (curChar.freq > 0) {
maxHeap.add(curChar);
}
}
}
return res.length() == s.length() ? res.toString() : "";
}
class CharInfo implements Comparable<CharInfo> {
char val;
int freq;
public CharInfo(char val, int freq) {
this.val = val;
this.freq = freq;
}
public int compareTo(CharInfo that) {
return that.freq - this.freq;
}
}
}
3. Time & Space Complexity