微软高频面试题Leetcode 767. 重构字符串

这道题是一个贪心模拟思路

首先,统计每个字符出现的次数,如果出现次数最多的数目满足如下关系,那么就一定不存在答案

        // aaab    偶数的情况,如果出现次数最多的字母次数大于n/2+1, 那么就一定不行

        // aab     奇数的情况,如果出现次数最多的字母次数大于(n+1)/2+1, 那么一定不行

我们先找到出现次数最多的字符,然后先把他放好,如下所示,然后再依次放其他

aXaXaXa...

放的时候有一个技巧,相同字符也一样隔一个往后放,放满后再回过头来从1往后放。

class Solution {
public:
    string reorganizeString(string S) {
        int hashmap[26] = {0};
        for(auto c:S) hashmap[c-'a']++;
        int maxCount = 0, maxIndex = 0;
        for(int i=0;i<26;i++){
            if(hashmap[i]>maxCount){
                maxCount = hashmap[i];
                maxIndex = i;
            }
        }
        // aaab    偶数的情况,如果出现次数最多的字母次数大于n/2+1, 那么就一定不行
        // aab     奇数的情况,如果出现次数最多的字母次数大于(n+1)/2+1, 那么一定不行

        if(2*maxCount-1>S.size()) return "";
        string res = S;
        int i = 0;
        while(hashmap[maxIndex]){
            res[i] = 'a'+maxIndex;
            i+=2;
            hashmap[maxIndex]--;
        }
        for(int j=0;j<26;j++){
            while(hashmap[j]){
                if(i>=S.size()) i = 1;
                res[i] = 'a' + j;
                i+=2;
                hashmap[j]--;
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/108504627
今日推荐