-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2384.cpp
More file actions
44 lines (41 loc) · 1.08 KB
/
2384.cpp
File metadata and controls
44 lines (41 loc) · 1.08 KB
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
class Solution {
public:
string largestPalindromic(string num) {
vector<int> counts(10, 0);
for (auto c : num) counts[c - '0']++;
string res;
for (int i = 9; i >= 1; --i) {
if (counts[i] >= 2) {
while (counts[i] > 1) {
res.push_back(i + '0');
counts[i] -= 2;
}
}
}
if (res.size() > 0) {
if (counts[0] >= 2) {
while (counts[0] > 1) {
res.push_back(0 + '0');
counts[0] -= 2;
}
}
}
// get the max middle
int maxMiddle = -1;
for (int i = 9; i >= 0; --i) {
if (counts[i] > 0) {
maxMiddle = i;
break;
}
}
string rev = res;
reverse(rev.begin(), rev.end());
if (maxMiddle != -1) {
res = res + to_string(maxMiddle) + rev;
}
else {
res = res + rev;
}
return res;
}
};