-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path767. Reorganize String
90 lines (77 loc) · 2.34 KB
/
767. Reorganize String
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
80
81
82
83
84
85
86
87
88
89
90
class Solution {
public:
std::string reorganizeString(std::string s) {
std::unordered_map<char, int> count;
for (char c : s) {
count[c]++;
}
std::vector<std::vector<int>> maxHeap;
for (auto entry : count) {
maxHeap.push_back({-entry.second, entry.first});
}
heapify(maxHeap);
std::vector<int> prev;
std::string res = "";
while (!maxHeap.empty() || !prev.empty()) {
if (!prev.empty() && maxHeap.empty()) {
return "";
}
std::vector<int> top = heapPop(maxHeap);
res += static_cast<char>(top[1]);
top[0]++;
if (!prev.empty()) {
heapPush(maxHeap, prev);
prev.clear();
}
if (top[0] != 0) {
prev = top;
}
}
return res;
}
private:
void heapify(std::vector<std::vector<int>>& heap) {
int n = heap.size();
for (int i = n / 2 - 1; i >= 0; i--) {
heapifyDown(heap, i);
}
}
void heapifyDown(std::vector<std::vector<int>>& heap, int index) {
int n = heap.size();
int left = 2 * index + 1;
int right = 2 * index + 2;
int largest = index;
if (left < n && heap[left][0] < heap[largest][0]) {
largest = left;
}
if (right < n && heap[right][0] < heap[largest][0]) {
largest = right;
}
if (largest != index) {
std::swap(heap[index], heap[largest]);
heapifyDown(heap, largest);
}
}
std::vector<int> heapPop(std::vector<std::vector<int>>& heap) {
int n = heap.size();
std::vector<int> top = heap[0];
heap[0] = heap[n - 1];
heap.pop_back();
heapifyDown(heap, 0);
return top;
}
void heapPush(std::vector<std::vector<int>>& heap, std::vector<int>& element) {
heap.push_back(element);
heapifyUp(heap, heap.size() - 1);
}
void heapifyUp(std::vector<std::vector<int>>& heap, int index) {
while (index > 0) {
int parent = (index - 1) / 2;
if (heap[index][0] >= heap[parent][0]) {
break;
}
std::swap(heap[index], heap[parent]);
index = parent;
}
}
};