Saturday, February 29, 2020

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: ""
Note:
  • S will consist of lowercase letters and have length in range [1, 500].

struct comp {
    bool operator()(pair<char, int>& first, pair<char, int>& second) {
        return first.second < second.second;
    }
};

class Solution {
public:
    string reorganizeString(string S) {
        string ans;
        if (S.size() == 0 || S.size() == 1) {
            return S;
        }
        // Similar to Task schedule problem with n = 1.
        map<char, int> mp;
        for (auto ch : S) {
            mp[ch]++;
        }
       
        priority_queue<pair<char, int>, vector<pair<char, int>>, comp> pq;
        for (auto entry : mp) {
            pq.push(entry);
        }
       
        while(!pq.empty()) {
            vector<pair<char, int>> remaining;
            for (int i = 0; i < 2; i++) {
                pair<char, int> entry = pq.top(); pq.pop();
                ans += entry.first;
                if(--entry.second > 0) {
                    remaining.push_back(entry);
                }
               
                if (pq.empty()) {
                    // No other char to insert after this one.
                    if (i == 0 && ans.size() != S.size()) {
                        return "";
                    }
                    break;
                }
            }
            for (auto entry : remaining) {
                pq.push(entry);
            }
        }
        return (ans.size() == S.size() ? ans : "");
    }
};

No comments:

Post a Comment