778. Reorganize String

Problem:

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

 

Solutions:

class Solution {
public:
    string reorganizeString(string S) {
        return rearrangeString(S, 2);
    }

private:
    string rearrangeString(string s, int k) {
        if (k <= 0) return s; // This special case if important
        if (s.length() == 0)    return s;

        int len = s.length();

        unordered_map<char, int> charCount;
        for (auto c : s) {
            ++charCount[c];
        }

        vector<char> chars;
        for (auto& entry : charCount) {
            chars.push_back(entry.first);
        }

        sort(chars.begin(), chars.end(), [charCount](char c1, char c2) {
           return charCount.at(c1) > charCount.at(c2); 
        });

        int maxVal = charCount[chars[0]];
        int maxCount = 0;
        for (int i = 0; i < chars.size() && charCount[chars[i]] == maxVal; ++i) ++maxCount;


        if (len < (k * (maxVal - 1) + maxCount)) return "";

        vector<string> matrix(maxVal - 1);
        int pos = 0;
        for (int i = maxCount; i < chars.size(); ++i) {
            for (int j = 0; j < charCount[chars[i]]; ++j) {
                matrix[pos%(maxVal - 1)].push_back(chars[i]);
                ++pos;
            }
        }

        string ret;
        string maxStr;
        for (int i = 0; i < maxCount; ++i) {
            maxStr.push_back(chars[i]);
        }

        for (int i = 0; i < maxVal - 1; ++i) {
            ret.append(maxStr);
            ret.append(matrix[i]);
        }
        ret.append(maxStr);
        return ret;
    }
};

results matching ""

    No results matching ""