LeetCode in Kotlin

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:

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

class Solution {
    fun largestPalindromic(num: String): String {
        val count = IntArray(10)
        var center = -1
        val first = StringBuilder()
        for (c in num.toCharArray()) {
            count[c.code - '0'.code]++
        }
        var c: Int
        for (i in 9 downTo 0) {
            c = 0
            if (count[i] % 2 == 1 && center == -1) {
                center = i
            }
            if (first.length == 0 && i == 0) {
                continue
            }
            while (c < count[i] / 2) {
                first.append(i.toString())
                c++
            }
        }
        val second: StringBuilder = StringBuilder(first.toString())
        if (center != -1) {
            first.append(center)
        }
        first.append(second.reverse().toString())
        return if (first.length == 0) "0" else first.toString()
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy