Given a non-empty string s and an integer k, rearrange the string such that the same characters are at least distance k from each other.
All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string ""
.
Example 1:
Input: s = "aabbcc", k = 3 Output: "abcabc" Explanation: The same letters are at least distance 3 from each other.
Example 2:
Input: s = "aaabc", k = 3 Output: "" Explanation: It is not possible to rearrange the string.
思路:這題其實是 Reorganize String 的升級版;這裏需要跳過K個了。這裏用個queue來存儲wait的node;
class Solution {
public class Node {
public char c;
public int fre;
public Node(char c, int fre) {
this.c = c;
this.fre = fre;
}
}
public class NodeComparator implements Comparator<Node> {
@Override
public int compare(Node a, Node b) {
return b.fre - a.fre;
}
}
public String rearrangeString(String s, int k) {
HashMap<Character, Integer> countMap = new HashMap<>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
countMap.put(c, countMap.getOrDefault(c, 0) + 1);
}
PriorityQueue<Node> pq = new PriorityQueue<Node>(new NodeComparator());
for(Character c : countMap.keySet()) {
pq.offer(new Node(c, countMap.get(c)));
}
StringBuilder sb = new StringBuilder();
Queue<Node> waitqueue = new LinkedList<Node>();
while(!pq.isEmpty()) {
Node node = pq.poll();
sb.append(node.c);
node.fre--;
countMap.put(node.c, countMap.get(node.c) - 1);
waitqueue.offer(node);
// 這裏不滿足就繼續,滿足了k,就要加入之前的node了;
// 比如abc了,那麼已經有3個了,那麼接下來就應該把a加入隊列了
if(waitqueue.size() < k) {
continue;
}
Node waitnode = waitqueue.poll();
if(waitnode.fre > 0) {
pq.offer(waitnode);
}
}
return sb.length() == s.length() ? sb.toString() : "";
}
}