forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0767-reorganize-string.cpp
44 lines (33 loc) · 977 Bytes
/
0767-reorganize-string.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Time: O(NlogN)
// Space: O(N)
class Solution {
public:
string reorganizeString(string s) {
string res="";
unordered_map<char, int> mp;
priority_queue<pair<int, char>> maxh;
for(auto ch : s)
mp[ch] += 1;
for(auto m : mp)
maxh.push(make_pair(m.second, m.first));
while(maxh.size() > 1){
auto top1= maxh.top();
maxh.pop();
auto top2 = maxh.top();
maxh.pop();
res += top1.second;
res += top2.second;
if(--top1.first > 0)
maxh.push(top1);
if(--top2.first > 0)
maxh.push(top2);
}
if(!maxh.empty()){
if(maxh.top().first > 1)
return "";
else
res += maxh.top().second;
}
return res;
}
};