#Leetcode# 767. Reorganize String

https://leetcode.com/problems/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: ""

Note:

  • S will consist of lowercase letters and have length in range [1, 500].

代码:

class Solution {
public:
    string reorganizeString(string S) {
        int len = S.length();
        string ans = "";
        unordered_map<char, int> mp;
        priority_queue<pair<int, char> > q;
        
        for(int i = 0; i < len; i ++)
            mp[S[i]] ++;
        
        for(auto i : mp) {
            if(i.second > (len + 1) / 2) return ans;
            else q.push({i.second, i.first});
        }
        
        while (q.size() >= 2) {
            auto t1 = q.top(); q.pop();
            auto t2 = q.top(); q.pop();
            ans.push_back(t1.second);
            ans.push_back(t2.second);
            if (--t1.first > 0) q.push(t1);
            if (--t2.first > 0) q.push(t2);
        }
        if (q.size() > 0) ans.push_back(q.top().second);
        return ans;
    }
};

  优先队列

FH 今天回家了!

猜你喜欢

转载自www.cnblogs.com/zlrrrr/p/10340633.html