2384. Largest Palindromic Number

Difficulty:
Related Topics:
Similar Questions:

Problem

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:

  Example 1:

Input: num = "444947137"
Output: "7449447"
Explanation: 
Use the digits "4449477" from "444947137" to form the palindromic integer "7449447".
It can be shown that "7449447" is the largest palindromic integer that can be formed.

Example 2:

Input: num = "00009"
Output: "9"
Explanation: 
It can be shown that "9" is the largest palindromic integer that can be formed.
Note that the integer returned should not contain leading zeroes.

  Constraints:

Solution

/**
 * @param {string} num
 * @return {string}
 */
var largestPalindromic = function(num) {
    var map = Array(10).fill(0);
    for (var i = 0; i < num.length; i++) {
        map[+num[i]]++;
    }
    var res = '';
    for (var j = map.length - 1; j >= 0; j--) {
        if (map[j] <= 1 || (j === 0 && res.length === 0)) continue;
        res = res.slice(0, res.length / 2)
            + String(j).repeat(map[j] % 2 ? (map[j] - 1) : map[j])
            + res.slice(res.length / 2);
        map[j] = map[j] % 2 ? 1 : 0;
    }
    for (var k = map.length - 1; k >= 0; k--) {
        if (map[k] === 0) continue;
        res = res.slice(0, res.length / 2)
            + String(k)
            + res.slice(res.length / 2);
        break;
    }
    return res;
};

Explain:

nope.

Complexity: