20.11.30 leetcode767

题目链接:https://leetcode-cn.com/problems/reorganize-string/

题意:给你一个字符串,问是否可以把字符串重新排列,使得任意相邻字母不同。

分析:不存在的情况就是出现次数最多的字母超过了ceil(len/2)。

排字母时要注意一个极限情况,就是字符串长度为奇数,且字母出现次数最多为(n+1)/2,如长度为7,最多字母出现次数为4,这时候这个字母只有一种排序方式,那就是填满所有偶数下标(0,2,4,6)。因为偶数下标可能被这种极端情况占用,故我们优先填充奇数下标,因为先填偶数下标可能会破坏这种极端情况,使得出现次数最多的字母无法填完。

class Solution {
public:
    string reorganizeString(string S) {
        int book[26];
        memset(book,0,sizeof(book));
        int n=S.size();
        if(n<=2)return S;
        for(int i=0;i<n;i++){
            book[S[i]-'a']++;
        }
        int mx=-1;
        for(int i=0;i<26;i++){
            mx=max(mx,book[i]);
        }
        //cout<<ceil(n/2.0);
        if(mx>ceil(n/2.0))return "";
        string ans(n,' ');
        int half=n/2;
        int evenIndex=0,oddIndex=1;
        for(int i=0;i<26;i++){
            char c=char(i+'a');
            while(book[i]>0&&book[i]<=half&&oddIndex<n){
                ans[oddIndex]=c;
                book[i]--;
                oddIndex+=2;
            }
            while(book[i]>0){
                ans[evenIndex]=c;
                book[i]--;
                evenIndex+=2;
            }
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/qingjiuling/p/14060140.html