[LeetCode] Reorganize String

767. Reorganize String

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.

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
class Solution {
public:
string reorganizeString(string s) {
unordered_map<char, int> m;
priority_queue<pair<int, char>> pq;
stringstream ss;
char prev = '*';
for(char& c : s) {
m[c]++;
}
for(auto& entity : m) {
pq.push({entity.second, entity.first});
}
while(!pq.empty()) {
auto p = pq.top();
pq.pop();
if(p.second != prev) {
prev = p.second;
ss << prev;
if(--p.first) {
pq.push(p);
}
} else {
if(pq.empty()) return "";
auto p2 = pq.top();
pq.pop();
pq.push(p);
if(p2.second != prev) {
prev = p2.second;
ss << prev;
if(--p2.first) {
pq.push(p2);
}
}
}
}
return ss.str();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/11/PS/LeetCode/reorganize-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.