-
Notifications
You must be signed in to change notification settings - Fork 0
/
noAdjacentChar.cpp
82 lines (70 loc) · 1.29 KB
/
noAdjacentChar.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* @file noAdjacentChar.cpp
* @author long ([email protected])
* @brief Rearrange characters in a String such that
* no two adjacent characters are same
* @version 0.1
* @date 2023-03-20
*
* @copyright Copyright (c) 2023
*
*/
#include <bits/stdc++.h>
using namespace std;
char getMaxCountChar(vector<int>& count) {
int max = 0;
char ch;
for (int i = 0; i < 26; i++) {
if (count[i] > max) {
max = count[i];
ch = 'a' + i;
}
}
return ch;
}
string rearrangeString(string S) {
int n = S.size();
if (n == 0) {
return "";
}
vector<int> count(26, 0);
for (auto& ch : S){
count[ch - 'a']++;
}
char ch_max = getMaxCountChar(count);
int maxCount = count[ch_max - 'a'];
if (maxCount > (n + 1) / 2) {
return "";
}
string res(n, ' ');
int ind = 0;
while (maxCount) {
res[ind] = ch_max;
ind = ind + 2;
maxCount--;
}
count[ch_max - 'a'] = 0;
for (int i = 0; i < 26; i++) {
while (count[i] > 0) {
ind = (ind >= n) ? 1 : ind;
res[ind] = 'a' + i;
ind += 2;
count[i]--;
}
}
return res;
}
int main()
{
int t;
cin >> t;
while (t--) {
string str;
cin >> str;
string res = rearrangeString(str);
if(res != "") {
cout << 1 << endl;
} else cout << -1 << endl;
}
return 0;
}