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].

// Hashmap + greedy + heap
string reorganizeString(string S) { // time: O(nlogn); space: O(n)
    int len = S.length();
    vector<int> count(26, 0);
    for (char ch : S) {
        if (count[ch - 'a'] > (len + 1) / 2) return "";
        ++count[ch - 'a'];
    }
    priority_queue<pair<int, char> > pq;
    for (int i = 0; i < 26; ++i) {
        if (!count[i]) continue;
        pq.push({count[i], (char)('a' + i)});
    }
    string res;
    while (!pq.empty()) {
        auto t = pq.top(); pq.pop();
        if (res.empty() || t.second != res[res.length() - 1]) {
            res += t.second;
            if (--t.first > 0) pq.push(t);
        } 
        else if (!pq.empty()) {
            auto u = pq.top(); pq.pop();
            res += u.second;
            if (--u.first > 0) pq.push(u);
            pq.push(t);
        } else {
            return "";
        }
    }
    return res;
}
358. Rearrange String k Distance Apartchevron-right621. Task Schedulerchevron-right

Last updated