首页 > 其他分享 >358 Rearrange String k Distance Apart 每个相同字母都要相距为k 767. Reorganize String k = 2

358 Rearrange String k Distance Apart 每个相同字母都要相距为k 767. Reorganize String k = 2

时间:2022-10-02 05:55:05浏览次数:48  
标签:count Distance String maxHeap 767 current string wait

Given a string s and an integer k, rearrange s such that the same characters are at least distance k from each other. 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 a distance of 3 from each other.

Example 2:

Input: s = "aaabc", k = 3
Output: ""
Explanation: It is not possible to rearrange the string.

Example 3:

Input: s = "aaadbbcc", k = 2
Output: "abacabcd"
Explanation: The same letters are at least a distance of 2 from each other.

 

Constraints:

  • 1 <= s.length <= 3 * 105
  • s consists of only lowercase English letters.
  • 0 <= k <= s.length

 

class Solution {
    /**
    和我的想法一样啊:从最多的开始放,abc abc ab ab a
    用hashmap:可以,但是写起来不快
    看来q也是一个常用的思路了
    参考:https://leetcode.com/problems/reorganize-string/discuss/128907/Java-solution-99-similar-to-358
    */
    public String rearrangeString(String S, int k) {
        Map<Character, Integer> count = new HashMap<>();
        
        for (char c : S.toCharArray()) {
            count.put(c, count.getOrDefault(c, 0) + 1);
        }
        
        //所有的都加入到pq中
        PriorityQueue<Character> maxHeap = new PriorityQueue<>((a, b) -> count.get(b) - count.get(a));
        maxHeap.addAll(count.keySet());
        
        //用于等待的q
        Queue<Character> wait = new LinkedList<>();
        //用于结果的sb
        StringBuilder sb = new StringBuilder();
        
        
        while(!maxHeap.isEmpty()) {
            //拿出来一个频率最高的,数量-1,同时放到wait中
            Character current = maxHeap.poll();
            sb.append(current);
            count.put(current, count.get(current) - 1);
            wait.offer(current);
            
            //一直在继续
            if (wait.size() < k) {
                continue;
            }
            
            //要是wait的第一个还有,就继续放进max heap
            Character front = wait.poll();
            if (count.get(front) > 0) {
                maxHeap.offer(front);
            }
        }
        
        return sb.length() == S.length() ? sb.toString() :"";
    }
}

 

标签:count,Distance,String,maxHeap,767,current,string,wait
From: https://www.cnblogs.com/immiao0319/p/16748198.html

相关文章