-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathReorganize String.cpp
48 lines (36 loc) · 1.17 KB
/
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
45
46
47
48
/*
Solution by Rahul Surana
***********************************************************
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.
***********************************************************
*/
class Solution {
public:
string reorganizeString(string s) {
vector<int> f(26,0);
for(auto x: s){
f[x-'a']++;
if(f[x-'a'] > (s.length()+1)/2 ) return "";
}
priority_queue<pair<int, char>> pq;
for(int i = 0; i < 26; i++){
if(f[i] > 0) pq.push({f[i], i+'a'});
}
string ans = "";
while(!pq.empty()){
auto a = pq.top();
pq.pop();
if(pq.empty()) return (ans+a.second);
auto b = pq.top();
pq.pop();
ans += a.second;
ans += b.second;
if(a.first > 1)
pq.push({a.first-1,a.second});
if(b.first > 1)
pq.push({b.first-1,b.second});
}
return ans;
}
};