Monday, August 10, 2020

767. Reorganize String --M

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


A:

constructive way, try to find the most appeared char , and use it .


class Solution {
public:
    string reorganizeString(string S) {
        vector<int> V(26,0);
        for(auto c : S)
            V[c-'a']++;
        
        string res = "";
        while(res.length() < S.length()){
            int maxCount = 0;// each time, find the char with max appearance
            char maxChar = 'a';
            for(int i =0;i<26;i++){
                if(V[i]>maxCount && ( res.length()==0 || ( (i+'a') != res.back() ) )){
                    maxChar = i+'a';
                    maxCount = V[i];
                }
            }
            if(maxCount==0){
                return "";
            }else{
                res += maxChar;
                V[maxChar -'a']--;
            }
        }
        return res;
        
    }
};




No comments:

Post a Comment