码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] reorganize String

时间:2019-02-06 19:42:38      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:vol   count   har   sage   +=   auto   begin   col   cond   

Runtime: 4 ms;
Memory Usage: 5 MB (好高啊魂淡!again
 
我懒死算了这样下去欠了多少债
//大致是参考solution1的思路
bool compare(pair<int,char>a, pair<int,char>b) {
    return a.first>b.first;
}

class Solution {
public:
    string reorganizeString(string S) {
        auto length=S.size();
        if (length<=1)
            return S;
        int counts[26]={0};
        for (int i=0;i<length;i++)
            ++counts[S[i]-a];
        int threshold=length/2+(length%2==0?0:1);
        for (int i=0;i<26;i++) {
            if (counts[i]>threshold)
                return "";
        }
        vector<pair<int,char>> characters_involved;
        for (int i=0;i<26;i++) {
            if (counts[i]>0) {
                characters_involved.push_back(make_pair(counts[i],a+i));
            }
        }
        sort(characters_involved.begin(), characters_involved.end(),compare);
        //sort characters_involved in decreasing order based on the counts.
        string answer(length,  );
        auto current_choice=characters_involved.begin();
        int current_position=0;
        while (current_choice!=characters_involved.end()) {
            answer[current_position]=current_choice->second;
            if (--(current_choice->first)==0)
                ++current_choice;
            current_position+=2;
            if (current_position>=length)
                current_position=1;
        }
        return answer;
    }
};

 

[leetcode] reorganize String

标签:vol   count   har   sage   +=   auto   begin   col   cond   

原文地址:https://www.cnblogs.com/RDaneelOlivaw/p/10353955.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!