天天看点

Rearrange String k Distance Apart

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 {
    private 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) {
        if(s == null || s.length() == 0) {
            return s;
        }
        HashMap<Character, Integer> countmap = new HashMap<>();
        PriorityQueue<Node> pq = new PriorityQueue<Node>((a, b) -> (b.fre - a.fre));
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            countmap.put(c, countmap.getOrDefault(c, 0) + 1);
        }
        
        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--;
            waitqueue.add(node);
            
            if(waitqueue.size() < k) {
                continue;
            }
            Node waitnode = waitqueue.poll();
            if(waitnode.fre > 0) {
                pq.offer(waitnode);
            }
        }
        return sb.length() == s.length() ? sb.toString() : "";
    }
}
           

继续阅读