767. Reorganize String

Medium

51927FavoriteShare

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]​​.
class Solution {
public:
//--按照大顶堆建堆
struct Cmp{
bool operator()(const pair<int,char>& x,const pair<int,char>& y){
return x.first < y.first;
}
};
string reorganizeString(string S){
unordered_map<char,int> HashMap;
for(auto s : S){
HashMap[s] ++;
}
priority_queue<pair<int,char>,vector<pair<int,char>>,Cmp> q;
for(auto i = HashMap.begin();i != HashMap.end();i++){
q.push(make_pair(i->second,i->first));
}
string Result;
while(!q.empty()){
if(q.size() == 1){
pair<int,char> tmp = q.top();
q.pop();
Result.insert(Result.end(),tmp.first,tmp.second);
}
else{
pair<int,char> First = q.top();
q.pop();
pair<int,char> Second = q.top();
q.pop();
if(First.first > 0){
Result.push_back(First.second);
First.first--;
if(First.first > 0){
q.push(First);
}
}
if(Second.first > 0){
Result.push_back(Second.second);
Second.first--;
if(Second.first > 0){
q.push(Second);
}
}
}
}
if(Result.length() >= 2 && Result[Result.length() - 1] == Result[Result.length() - 2]){
Result = "";
}
return Result;
}

};

 

priority_queue本质是一个堆。

1. 头文件是#include<queue>

2. 关于priority_queue中元素的比较

  模板申明带3个参数:priority_queue<Type, Container, Functional>,其中Type 为数据类型,Container为保存数据的容器,Functional 为元素比较方式。

  Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector。

2.1 比较方式默认用operator<,所以如果把后面2个参数缺省的话,优先队列就是大顶堆(降序),队头元素最大。

关于重载()的函数对象Cmp的相关用法请看以下链接:​​相关链接​​,注意大顶堆是默认比较的,运算符重载为operator<