[leetcode] reorganize String
Posted rdaneelolivaw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] reorganize String相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
sql server中index的REBUILD和REORGANIZE
Use Word 2010's Navigation Pane to quickly reorganize documents