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 {
class Node {
public char c;
public int fre;
public Node(char c, int fre) {
this.c = c;
this.fre = fre;
}
}
public String rearrangeString(String s, int k) {
HashMap<Character, Integer> hashmap = new HashMap<>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
hashmap.put(c, hashmap.getOrDefault(c, 0) + 1);
}
PriorityQueue<Node> pq = new PriorityQueue<Node>((a, b) ->(b.fre - a.fre));
for(Character c: hashmap.keySet()) {
pq.offer(new Node(c, hashmap.get(c)));
}
StringBuilder sb = new StringBuilder();
Queue<Node> tempqueue = new LinkedList<>();
while(!pq.isEmpty()) {
Node node = pq.poll();
sb.append(node.c);
node.fre--;
tempqueue.offer(node);
if(tempqueue.size() < k) {
continue;
}
node = tempqueue.poll();
if(node != null && node.fre > 0) {
pq.offer(node);
}
}
return sb.length() == s.length() ? sb.toString() : "";
}
}