leetcode 767. Reorganize String

Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

If possible, output any possible result. If not possible, return the empty string.

Example 1:

Input: S = "aab"
Output: "aba"
Example 2:

Input: S = "aaab"
Output: ""

题目大意给出一个字符串,重新排列字符串使得相邻的两个字母不相同,并输出这个重新排列后的字符串,如果没有符合条件的就返回空字符串。
思路:贪心,每次把数量最多的2个字母配对,添加到构造的字符串中。这样能保证后面构造时的成功性最高。用优先队列实现。

class Solution {
public:
    string reorganizeString(string S) {
        map<char, int> mp;
        for (int i = 0; i < S.size(); ++i) {
            mp[S[i]]++;
        }
        priority_queue< pair<int, char> > q;
        for (auto x : mp) {
            q.push({x.second, x.first});
        }
        string s = "";
        while (!q.empty()) {
            pair<int, char> u, v;
            u = q.top();
            q.pop();
            if (u.first > 0) {
                s += u.second;
                --u.first;
                if (q.empty()) break;
                v = q.top();
                q.pop();
                if (v.first > 0) {
                    s += v.second;
                    --v.first;
                    q.push(v);
                } else {
                    break;
                }
                q.push(u);
            } 
        }
        if (s.size() != S.size()) return "";
        return s;
    }
};
原文地址:https://www.cnblogs.com/pk28/p/8483115.html