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

 

Approach #1 Sort by count:

class Solution {
public:
    string reorganizeString(string S) {
        int len = S.length();
        vector<int> count(26, 0);
        string ans = S;
        for (auto s : S) count[s-'a'] += 100;
        for (int i = 0; i < 26; ++i) count[i] += i;
        sort(count.begin(), count.end());
        int start = 1;
        int mid = (len + 1) / 2;
        for (int i = 0; i < 26; ++i) {
            int times = count[i] / 100;
            char c = 'a' + (count[i] % 100);
            if (times > mid) return "";
            for (int j = 0; j < times; ++j) {
                if (start >= len) start = 0;
                ans[start] = c;
                start += 2;
            }
        }
        //ans += '\0';
        return ans;
    }
};
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Reorganize String.

 

 

posted @ 2018-10-31 16:55  Veritas_des_Liberty  阅读(245)  评论(0编辑  收藏  举报