-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLC767.cpp
79 lines (54 loc) · 1.76 KB
/
LC767.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
767. Reorganize String
Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.
Return any possible rearrangement of s or return "" if not possible.
Example 1:
Input: s = "aab"
Output: "aba"
Example 2:
Input: s = "aaab"
Output: ""
Constraints:
1 <= s.length <= 500
s consists of lowercase English letters.
*/
class Solution {
public:
string reorganizeString(string s) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
typedef std::pair<char, int> PairT;
auto cmp = [&](PairT a, PairT b) { return a.second < b.second; };
typedef std::unordered_map<char, int> FreqMapT;
FreqMapT freq_map;
FreqMapT::iterator freq_iter;
for (auto elem : s) {
freq_iter = freq_map.find(elem);
if (freq_iter != freq_map.end()) {
freq_iter->second++;
}
else
freq_map.insert({elem, 0});
}
std::string result;
std::priority_queue<PairT, std::vector<PairT>, decltype(cmp)> maxHeap{cmp};
for (auto [first, second] : freq_map) {
maxHeap.push({first, second});
}
auto start = maxHeap.top(); maxHeap.pop();
result.push_back(start.first);
start.second--;
while (!maxHeap.empty()) {
auto temp = maxHeap.top(); maxHeap.pop();
result.push_back(temp.first);
temp.second--;
if (start.second >= 0) {
maxHeap.push(start);
}
start = temp;
}
if (start.second >= 0)
return "";
return result;
}
};