Palindromic Number - devil is in the details

This problem is more labor intensive than hard. You got to just keep an eye on the details. Using the bucket count approach, create the largest palindrome, but keep an eye on the "0"s. Code is below, cheers, ACC.

Largest Palindromic Number - LeetCode

2384. Largest Palindromic Number
Medium

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.

 

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:

  • 1 <= num.length <= 105
  • num consists of digits.

public class Solution {
    public string LargestPalindromic(string num)
    {
        int[] count = new int[10];

        foreach (char c in num)
            count[(int)(c - '0')]++;

        string retVal = "";
        int highestOdd = -1;
        for (int i = 9; i >= 0; i--)
        {
            int numberChars = count[i];

            if (numberChars % 2 == 0)
            {
                string partCentral = (new string((char)(i + '0'), numberChars));
                if (String.IsNullOrEmpty(retVal)) retVal = partCentral;
                else retVal = retVal.Substring(0, retVal.Length / 2) + partCentral + retVal.Substring(retVal.Length / 2);
            }
            else
            {
                highestOdd = Math.Max(highestOdd, i);
                if (numberChars > 1)
                {
                    string partCentral = (new string((char)(i + '0'), numberChars - 1));
                    if (String.IsNullOrEmpty(retVal)) retVal = partCentral;
                    else retVal = retVal.Substring(0, retVal.Length / 2) + partCentral + retVal.Substring(retVal.Length / 2);
                }
            }
        }

        if (highestOdd > -1)
        {
            if (String.IsNullOrEmpty(retVal) || retVal.StartsWith("0")) retVal = ((char)(highestOdd + '0')).ToString();
            else retVal = retVal.Substring(0, retVal.Length / 2) + ((char)(highestOdd + '0')).ToString() + retVal.Substring(retVal.Length / 2);
        }

        if (retVal.StartsWith("0")) retVal = "0";

        return retVal;
    }
}


Comments

Popular posts from this blog

Changing the root of a binary tree

ProjectEuler Problem 719 (some hints, but no spoilers)

The Power Sum, a recursive problem by HackerRank