358. Rearrange String k Distance Apart

对给定字符串重排序,使得两个相同字符之间至少间隔k。靠直觉贪心做,对i从能放在i的可选字符中选剩下数目最多放入。如果不是选数目最多的放入最后它们剩下来就凑不足其它元素来间隔开它们。比如aaabbc, k = 1; 不先选掉a的话会成为bcbaaa, 但其实可以组成ababac。

class Solution {
public:
    string rearrangeString(string str, int k) {
        vector<int> count(26), valid(26);
        for (const auto c : str) {
            ++count[c - 'a'];
        }
        const auto next = [&](int index) {
            int mx = 0, res = -1;
            for (int i = 0; i < 26; ++i) {
                if (count[i] > mx && valid[i] <= index) {
                    res = i;
                    mx = count[i];
                }
            }
            return (char) (res + 'a'); 
        };
        string res;
        for (int i = 0; i < str.length(); ++i) {
            auto nc = next(i);
            res += nc;
            --count[nc - 'a'];
            valid[nc - 'a'] += i + k - 1;
        }
        return res;
    }
};

Last updated