|
| 1 | +// Source : https://leetcode.com/problems/largest-number-after-mutating-substring/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-11-12 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * You are given a string num, which represents a large integer. You are also given a 0-indexed |
| 8 | + * integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d |
| 9 | + * maps to digit change[d]. |
| 10 | + * |
| 11 | + * You may choose to mutate a single substring of num. To mutate a substring, replace each digit |
| 12 | + * num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]). |
| 13 | + * |
| 14 | + * Return a string representing the largest possible integer after mutating (or choosing not to) a |
| 15 | + * single substring of num. |
| 16 | + * |
| 17 | + * A substring is a contiguous sequence of characters within the string. |
| 18 | + * |
| 19 | + * Example 1: |
| 20 | + * |
| 21 | + * Input: num = "132", change = [9,8,5,0,3,6,4,2,6,8] |
| 22 | + * Output: "832" |
| 23 | + * Explanation: Replace the substring "1": |
| 24 | + * - 1 maps to change[1] = 8. |
| 25 | + * Thus, "132" becomes "832". |
| 26 | + * "832" is the largest number that can be created, so return it. |
| 27 | + * |
| 28 | + * Example 2: |
| 29 | + * |
| 30 | + * Input: num = "021", change = [9,4,3,5,7,2,1,9,0,6] |
| 31 | + * Output: "934" |
| 32 | + * Explanation: Replace the substring "021": |
| 33 | + * - 0 maps to change[0] = 9. |
| 34 | + * - 2 maps to change[2] = 3. |
| 35 | + * - 1 maps to change[1] = 4. |
| 36 | + * Thus, "021" becomes "934". |
| 37 | + * "934" is the largest number that can be created, so return it. |
| 38 | + * |
| 39 | + * Example 3: |
| 40 | + * |
| 41 | + * Input: num = "5", change = [1,4,7,5,3,2,5,6,9,4] |
| 42 | + * Output: "5" |
| 43 | + * Explanation: "5" is already the largest number that can be created, so return it. |
| 44 | + * |
| 45 | + * Constraints: |
| 46 | + * |
| 47 | + * 1 <= num.length <= 10^5 |
| 48 | + * num consists of only digits 0-9. |
| 49 | + * change.length == 10 |
| 50 | + * 0 <= change[d] <= 9 |
| 51 | + ******************************************************************************************************/ |
| 52 | + |
| 53 | +class Solution { |
| 54 | +public: |
| 55 | + string maximumNumber(string num, vector<int>& change) { |
| 56 | + bool replace = false; |
| 57 | + for(int i=0; i<num.size(); i++) { |
| 58 | + char n = num[i] - '0'; |
| 59 | + if (n < change[n] ) { |
| 60 | + num[i] = change[n] + '0'; |
| 61 | + replace = true; |
| 62 | + }else if (n > change[n] && replace ) { |
| 63 | + break; |
| 64 | + } |
| 65 | + } |
| 66 | + return num; |
| 67 | + } |
| 68 | +}; |
0 commit comments