[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 any 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) any 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

子字符串突变后可能得到的最大整数。

给你一个字符串 num ,该字符串表示一个大整数。另给你一个长度为 10 且 下标从 0  开始 的整数数组 change ,该数组将 0-9 中的每个数字映射到另一个数字。更规范的说法是,数字 d 映射为数字 change[d] 。

你可以选择 突变  num 的任一子字符串。突变 子字符串意味着将每位数字 num[i] 替换为该数字在 change 中的映射(也就是说,将 num[i] 替换为 change[num[i]])。

请你找出在对 num 的任一子字符串执行突变操作(也可以不执行)后,可能得到的 最大整数 ,并用字符串表示返回。

子字符串 是字符串中的一个连续序列。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/largest-number-after-mutating-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题的思路是贪心。题目问是否有可能根据change数组的情况,合理替换某一段数字(子串)从而使得替换之后的数字比原来的数字更大。所以为了能使结果更大,我们需要试图从 input 字符串的最左边,也就是数字的最高位开始试图替换。如果能把某一位数字替换得更大,则替换,并用一个 flag 记录我们已经开始替换了。如果这一路下去一直可以替换一个更大的数字或者起码保持不变,那么就一直走下去;如果已经开始替换了但是中间遇到一个地方只能换成一个小的数字,则在这里停下。已经置换的部分即是题意要求的子串。返回替换后的结果即可。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public String maximumNumber(String num, int[] change) {
 3         char[] chars = num.toCharArray();
 4         boolean changed = false;
 5         for (int i = 0; i < chars.length; i++) {
 6             int cur = chars[i] - '0';
 7             int candidate = change[cur];
 8             if (candidate > cur) {
 9                 chars[i] = (char) (candidate + '0');
10                 changed = true;
11             }
12             if (candidate < cur && changed) {
13                 break;
14             }
15         }
16         return new String(chars);
17     }
18 }

 

LeetCode 题目总结

上一篇:1037 在霍格沃茨找零钱 (20 分)


下一篇:MySQL实战45讲(06--10)