Reorganize String
#include<iostream>
#include<string>
#include<algorithm>
#include<unordered_map>
#include<queue>
using namespace std;
class Solution {
public:
string reorganizeString(string s) {
unordered_map<char, int> um;
priority_queue<pair<int, char>> pq;
string output = "";
for (auto i : s)
um[i]++;
for (auto &i : um)
pq.push({i.second, i.first});
while (pq.size() > 1) {
auto top1 = pq.top(); pq.pop();
auto top2 = pq.top(); pq.pop();
output += top1.second;
output += top2.second;
if (--top1.first > 0){
pq.push(top1);
}
if (--top2.first > 0){
pq.push(top2);
}
}
if (pq.size()) {
if (pq.top().first == 1)
output += pq.top().second;
else
return "";
}
return output;
}
};
int main(){
string s = "aaaaaccbbb";
Solution o;
cout<<o.reorganizeString(s);
}
# ./a.out
abacabacba
Are there any code examples left?
New code examples in category C++
-
C++ 2023-04-28 17:44:25
-
C++ 2022-03-27 19:20:39 lists occurrences of characters in the string c++
-
C++ 2022-03-27 18:00:14 variabili in c++
-
C++ 2022-03-27 17:10:08 repeat character n times c++
-
C++ 2022-03-27 15:50:07 delete an array c++
-
C++ 2022-03-27 15:40:12 C++ pointer to base class
-
C++ 2022-03-27 12:15:21 find the graph is minimal spanig tree or not
-
C++ 2022-03-27 11:30:15 multi variable assignment cpp
-
C++ 2022-03-27 11:05:17 c++ pi float
-
C++ 2022-03-27 10:20:12 why exceptions can lead to memory leaks