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

代码:

class Solution {
public:
    string reorganizeString(string S) {
        if(S.size() <= 1) return S;
        int chnum[26] = {0};
        for(int i = 0; i < S.size(); i++){
            chnum[S[i]-'a']++;
        }
        for(int i = 0; i < 26; i++){
            chnum[i] = chnum[i] * 100 + i;
        }
        sort(chnum, chnum+26);
        char res[S.size() + 1];
        res[S.size()] = '\0';
        int index = 1;
        for(int i = 0; i < 26; i++){
            char c = chnum[i] % 100 + 'a';
            int count = chnum[i] / 100;
            if(count > (S.size()+1)/2) return "";
            for(int j = 0; j < count; j++){
                if(index >= S.size()){
                    index = 0;
                }
                res[index] = c;
                index += 2;
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/jing16337305/article/details/80245548