-
Notifications
You must be signed in to change notification settings - Fork 166
/
String Reorder.cpp
48 lines (41 loc) · 1.05 KB
/
String Reorder.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
#include <bits/stdc++.h>
using namespace std;
const int maxN = 1e6+5;
int freq[26];
char S[maxN], ans[maxN];
bool possible(int current){
int mode = 0, total = 0;
for(int c = 0; c < 26; c++){
if(freq[mode] < freq[c])
mode = c;
total += freq[c];
}
return (freq[mode] <= (total+1)/2) && (freq[current] <= total/2);
}
int main(){
scanf(" %s", S);
const int N = (int) strlen(S);
for(int i = 0; i < N; i++)
freq[(int) (S[i] - 'A')]++;
int lastchar = -1;
for(int i = 0; i < N; i++){
bool filled = false;
for(int c = 0; c < 26 && !filled; c++){
if(freq[c] > 0 && c != lastchar){
freq[c]--;
if(possible(c)){
ans[i] = (char) (c + 'A');
lastchar = c;
filled = true;
} else freq[c]++;
}
}
if(!filled){
printf("-1\n");
return 0;
}
}
for(int i = 0; i < N; i++)
printf("%c", ans[i]);
printf("\n");
}