LeetCode每日一题(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.

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.

统计出 0-9 每个数字的计数, 然后我们把每个计数除以 2,就是该数字能出现在回文中一侧的数量, 如果计数 mod 2 等于 1 则证明该数字可以作为回文的中心, 反之如果等于 0, 则不能。

我们只需要建立回文的一侧即可, 另一侧将建立好的字符串反向拼接上就好。

建立时我们按 9 到 0 的顺序检查每个数字的计数, 注意这里的计数是指已经在原计数的基础上除以 2 的计数, 只要 count > 0 我们就可以将 count 个该数字放到答案中。注意, 如果第一次遍历直到 0 才发现 count > 0, 那我们不能把 0 放到答案中, 因为开头不能为 0。回文侧面选好了, 剩下的就是选择回文中心,还是从 9 到 0 来遍历, 如果该数字的原计数 mod 2 等于 1, 我们就可以拿它当回文中心, 因为中心只有一个, 所以选择完成后就不用再继续遍历下去了。

这里会遇到一种特殊情况, 就是只有 0,且 0 的计数为偶数, 这样的话无论是选侧面还是选中心, 0 都不会被选上, 返回的答案会是空字符串, 我们需要对这种情况进行检查,并且直接返回"0"作为答案


impl Solution {
    pub fn largest_palindromic(num: String) -> String {
        let mut freqs = num.chars().fold(vec![0; 10], |mut l, n| {
            l[n as usize - 48] += 1;
            l
        });
        let remains: Vec<i32> = freqs.iter().map(|&c| c % 2).collect();
        freqs = freqs.into_iter().map(|c| c / 2).collect();
        let mut is_begining = true;
        let mut ans = Vec::new();
        for i in (0..10usize).rev() {
            if freqs[i] > 0 {
                if i == 0 && is_begining {
                    break;
                }
                ans.append(&mut vec![((i + 48) as u8) as char; freqs[i] as usize]);
                is_begining = false;
            }
        }
        let mut is_single_center = false;
        for i in (0..10usize).rev() {
            if remains[i] > 0 {
                ans.push(((i + 48) as u8) as char);
                is_single_center = true;
                break;
            }
        }
        if ans.is_empty() {
            return "0".into();
        }
        let mut rev = ans.clone();
        if is_single_center {
            rev.pop();
        }
        rev.reverse();
        ans.append(&mut rev);
        ans.into_iter().collect()
    }
}

你可能感兴趣的:(leetcode,算法,职场和发展)