LeetCode每日一题(1946. Largest Number After Mutating Substring)

You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d].

You may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]).

Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num.

A substring is a contiguous sequence of characters within the string.

Example 1:

Input: num = “132”, change = [9,8,5,0,3,6,4,2,6,8] Output: “832”

Explanation: Replace the substring “1”:

    1 maps to change[1] = 8. Thus, “132” becomes “832”. “832” is the largest number that can be created, so return it.

Example 2:

Input: num = “021”, change = [9,4,3,5,7,2,1,9,0,6] Output: “934”

Explanation: Replace the substring “021”:

    0 maps to change[0] = 9. 2 maps to change[2] = 3. 1 maps to change[1] = 4. Thus, “021” becomes “934”. “934” is the largest number that can be created, so return it.

Example 3:

Input: num = “5”, change = [1,4,7,5,3,2,5,6,9,4] Output: “5”

Explanation: “5” is already the largest number that can be created, so return it.

Constraints:

    1 <= num.length <= 105 num consists of only digits 0-9. change.length == 10 0 <= change[d] <= 9

chenge 分为增长的和降低的, 我们要得到最大的数自然只考虑增长的, 所以我们要先把 0-9 的变化中增长的变化过滤出来, 其次,单个数位的数字变化,自然是位数越高所带来的影响越大,所以相同的变化我们自然是考虑更高位的变化, 题目里又告诉我们可以选择一个子字符串进行变化,但是子字符串必须是连续的, 这样我们就可以把题目转化成,从左到右遍历字符串,从找到的第一个(最高位)增长的 change 开始后面连续的 n 位(n >= 0)增长的 change, 只要做完这些 change,我们的字符串就是最大的数字了


use std::collections::HashMap;

impl Solution {
          
   
    pub fn maximum_number(num: String, change: Vec<i32>) -> String {
          
   
        let mut chars: Vec<char> = num.chars().collect();
        let increases: HashMap<char, char> = change
            .iter()
            .enumerate()
            .filter(|&(i, &v)| v as usize >= i)
            .map(|(i, &v)| {
          
   
                (
                    i.to_string().chars().nth(0).unwrap(),
                    v.to_string().chars().nth(0).unwrap(),
                )
            })
            .collect();
        let mut is_started = false;
        for i in 0..chars.len() {
          
   
            if let Some(&c) = increases.get(&(chars[i])) {
          
   
                if c != chars[i] {
          
   
                    is_started = true;
                    chars[i] = c;
                }
            } else {
          
   
                if is_started {
          
   
                    break;
                }
            }
        }
        chars.into_iter().collect()
    }
}
经验分享 程序员 微信小程序 职场和发展