1. 程式人生 > 其它 >[LeetCode] 1946. Largest Number After Mutating Substring

[LeetCode] 1946. Largest Number After Mutating Substring

You are given a stringnum, which represents a large integer. You are also given a0-indexedinteger arraychangeof length10that maps each digit0-9to another digit. More formally, digitdmaps to digitchange[d].

You may choose tomutateany substring ofnum. To mutate a substring, replace each digitnum[i]with the digit it maps to inchange

(i.e. replacenum[i]withchange[num[i]]).

Returna string representing thelargestpossible integer aftermutating(or choosing not to) any substring ofnum.

Asubstringis 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, "1
32" 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
  • numconsists of only digits0-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 題目總結