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;
}
// Hashmap + greedy + heap
string reorganizeString(string S) { // time: O(nlogn); space: O(n)
    vector<int> count(26, 0);
    for (char ch : S) {
        if (++count[ch - 'a'] > (S.length() + 1) / 2) return "";
    }
    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.size() >= 2) {
        auto t = pq.top(); pq.pop();
        auto u = pq.top(); pq.pop();
        res.push_back(t.second);
        res.push_back(u.second);
        if (--t.first > 0) pq.push(t);
        if (--u.first > 0) pq.push(u);
    }
    if (!pq.empty()) res.push_back(pq.top().second);
    return res;
}
358. Rearrange String k Distance Apart621. Task Scheduler

Last updated

Was this helpful?