2384. Largest Palindromic Number
You are given a string num consisting of digits only.
Return the largest palindromic integer (in the form of a string) that can be formed using digits taken from num. It should not contain leading zeroes.
Notes:
- You do not need to use all the digits of num, but you must use at least one digit.
- The digits can be reordered.
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
| class Solution { public: string largestPalindromic(string num) { unordered_map<char, int> freq; for(auto& n : num) freq[n]++; string res = ""; char ma = '#'; for(char ch = '9'; ch >= '0'; ch--) { int cnt = freq[ch] / 2; res += string(cnt, ch); freq[ch] %= 2; } for(char ch = '0'; ch <= '9'; ch++) { if(freq[ch]) ma = ch; } if(res[0] == '0') { if(ma == '#') return "0"; return string(1,ma); } string rev = res; reverse(begin(rev), end(rev)); if(ma != '#') return res + ma + rev; return res + rev; } };
|