-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmake-string-anti-palindrome.cpp
101 lines (98 loc) · 2.64 KB
/
make-string-anti-palindrome.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Time: O(n + 26)
// Space: O(26)
// counting sort, greedy
class Solution {
public:
string makeAntiPalindrome(string s) {
vector<int> cnt(26);
for (const auto& x : s) {
++cnt[x - 'a'];
}
if (ranges::max(cnt) > size(s) / 2) {
return "-1";
}
string result(size(s), 0);
for (int i = 0, j = 0; i < size(cnt); ++i) {
for (int _ = 0; _ < cnt[i]; ++_) {
result[j++] = 'a' + i;
}
}
int l = 0;
for (; l <= (size(s) / 2) / 2; ++l) {
if (result[size(s) / 2 + l] != result[size(s) / 2 - 1]) {
break;
}
}
if (l) {
for (int i = 0; i < cnt[result[size(s) / 2 - 1] - 'a'] - l; ++i) {
swap(result[size(s) / 2 + i], result[size(s) / 2 + i + l]);
}
}
return result;
}
};
// Time: O(n + 26)
// Space: O(26)
// counting sort, greedy, two pointers
class Solution2 {
public:
string makeAntiPalindrome(string s) {
vector<int> cnt(26);
for (const auto& x : s) {
++cnt[x - 'a'];
}
if (ranges::max(cnt) > size(s) / 2) {
return "-1";
}
string result(size(s), 0);
for (int i = 0, j = 0; i < size(cnt); ++i) {
for (int _ = 0; _ < cnt[i]; ++_) {
result[j++] = 'a' + i;
}
}
int left = size(s) / 2;
int right = left + 1;
for (; right < size(s) && result[right] == result[left]; ++right);
for (; result[left] == result[(size(s) - 1) - left]; ++left, ++right) {
swap(result[left], result[right]);
}
return result;
}
};
// Time: O(n * 26)
// Space: O(26)
// freq table, greedy
class Solution3 {
public:
string makeAntiPalindrome(string s) {
vector<int> cnt(26);
for (const auto& x : s) {
++cnt[x - 'a'];
}
if (ranges::max(cnt) > size(s) / 2) {
return "-1";
}
string result(size(s), 0);
for (int i = 0; i < size(s) / 2; ++i) {
int j = 0;
for (; j < size(cnt); ++j) {
if (cnt[j]) {
break;
}
}
--cnt[j];
result[i] = 'a' + j;
}
for (int i = size(s) / 2; i < size(s); ++i) {
int j = 0;
for (; j < size(cnt); ++j) {
if (cnt[j] && result[(size(s) - 1) - i] != 'a' + j) {
break;
}
}
--cnt[j];
result[i] = 'a' + j;
}
return result;
}
};