forked from sachuverma/DataStructures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reorganize String.cpp
66 lines (54 loc) · 1.06 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
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.
*/
string reorganizeString(string &A)
{
int n = A.size();
unordered_map<char, int> C;
for (auto &i : A)
{
C[i]++;
if (C[i] > (n + 1) / 2)
return "";
}
priority_queue<pair<int, char>> pq;
for (auto &i : C)
pq.push({i.second, i.first});
string B;
while (pq.size())
{
auto First = pq.top();
pq.pop();
auto Second = pq.top();
pq.pop();
if (First.first > 0)
{
B += (First.second);
First.first--;
}
else
break;
if (Second.first > 0)
{
B += (Second.second);
Second.first--;
}
else
break;
pq.push({First.first, First.second});
pq.push({Second.first, Second.second});
}
return B;
}