[LeetCode] Rearrange String k Distance Apart 按距离为k隔离重排字符串

Given a non-empty string str 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:

str = "aabbcc", k = 3

Result: "abcabc"

The same letters are at least distance 3 from each other.

Example 2:

str = "aaabc", k = 3 

Answer: ""

It is not possible to rearrange the string.

Example 3:

str = "aaadbbcc", k = 2

Answer: "abacabcd"

Another possible answer is: "abcabcda"

The same letters are at least distance 2 from each other.

Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.

这道题给了我们一个字符串str,和一个整数k,让我们对字符串str重新排序,使得其中相同的字符之间的距离不小于k,这道题的难度标为Hard,看来不是省油的灯。的确,这道题的解法用到了哈希表,堆,和贪婪算法。这道题我最开始想的算法没有通过OJ的大集合超时了,下面的方法是参考网上大神的解法,发现十分的巧妙。我们需要一个哈希表来建立字符和其出现次数之间的映射,然后需要一个堆来保存这每一堆映射,按照出现次数来排序。然后如果堆不为空我们就开始循环,我们找出k和str长度之间的较小值,然后从0遍历到这个较小值,对于每个遍历到的值,如果此时堆为空了,说明此位置没法填入字符了,返回空字符串,否则我们从堆顶取出一对映射,然后把字母加入结果res中,此时映射的个数减1,如果减1后的个数仍大于0,则我们将此映射加入临时集合v中,同时str的个数len减1,遍历完一次,我们把临时集合中的映射对由加入堆中,参见代码如下:

class Solution {
public:
    string rearrangeString(string str, int k) {
        if (k == 0) return str;
        string res;
        int len = (int)str.size();
        unordered_map<char, int> m;
        priority_queue<pair<int, char>> q;
        for (auto a : str) ++m[a];
        for (auto it = m.begin(); it != m.end(); ++it) {
            q.push({it->second, it->first});
        }
        while (!q.empty()) {
            vector<pair<int, int>> v;
            int cnt = min(k, len);
            for (int i = 0; i < cnt; ++i) {
                if (q.empty()) return "";
                auto t = q.top(); q.pop();
                res.push_back(t.second);
                if (--t.first > 0) v.push_back(t);
                --len;
            }
            for (auto a : v) q.push(a);
        }
        return res;
    }
};

参考资料:

https://leetcode.com/discuss/108174/c-unordered_map-priority_queue-solution-using-cache

LeetCode All in One 题目讲解汇总(持续更新中...)

时间: 2024-10-21 16:57:53

[LeetCode] Rearrange String k Distance Apart 按距离为k隔离重排字符串的相关文章

[LeetCode] 243. Shortest Word Distance 最短单词距离

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. For example,Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. G

LeetCode &quot;Rearrange String k Distance Apart&quot;

Greedy using priority_queue and hashmap. The basic idea is to have k buckets - and we fill it greedily. And I agree that the code below can be cleaner: struct Rec { Rec(char _c, int _cnt) :c(_c), cnt(_cnt) {} char c; int cnt; }; struct Cmp { bool ope

[LeetCode] 244. Shortest Word Distance II 最短单词距离 II

This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it? Design a class which receives a list

LeetCode | 1385. Find the Distance Value Between Two Arrays两个数组间的距离值【Python】

LeetCode 1385. Find the Distance Value Between Two Arrays两个数组间的距离值[Easy][Python][暴力] Problem LeetCode Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. The distance value is defined as the nu

【leetcode】1320. Minimum Distance to Type a Word Using Two Fingers

题目如下: You have a keyboard layout as shown above in the XY plane, where each English uppercase letter is located at some coordinate, for example, the letter A is located at coordinate (0,0), the letter B is located at coordinate (0,1), the letter P is

LeetCode: Interleaving String

LeetCode: Interleaving String Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: s1 = "aabcc", s2 = "dbbca", When s3 = "aadbbcbcac", return true. When s3 = "aadbbbaccc"

从K近邻算法、距离度量谈到KD树、SIFT+BBF算法

从K近邻算法.距离度量谈到KD树.SIFT+BBF算法 从K近邻算法.距离度量谈到KD树.SIFT+BBF算法 前言 前两日,在微博上说:“到今天为止,我至少亏欠了3篇文章待写:1.KD树:2.神经网络:3.编程艺术第28章.你看到,blog内的文章与你于别处所见的任何都不同.于是,等啊等,等一台电脑,只好等待..”.得益于田,借了我一台电脑(借他电脑的时候,我连表示感谢,他说“能找到工作全靠你的博客,这点儿小忙还说,不地道”,有的时候,稍许感受到受人信任也是一种压力,愿我不辜负大家对我的信任)

Leetcode:Scramble String 解题报告

Scramble String Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = "great": great / gr eat / \ / g r e at / a t To scramble the string,

leetcode第一刷_Edit Distance

最小编辑距离,很经典的问题,今年微软实习生的笔试有一个这个的扩展版,牵扯到模板之类的,当时一行代码也没写出来.. dp可以很优雅的解决这个问题,状态转移方程也很明确.用pos[i][j]表示word1的前i个字符与word2的前j个字符之间的编辑距离.如果word[i-1]与word[j-1]相等,那pos[i][j]与pos[i-1][j-1]相等,否则的话,根据编辑的几种操作,可以从三种情况中选取代价最小的一种,从word1中删除一个字符?从word2中删除一个字符?修改其中一个?边界也很简