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 thelargest possible integer after
mutating (or choosing not to) a single substring of _num.
A substring is a contiguous sequence of characters within the string.
Input: num ="_1_ 32", change =[9,8,5,0,3,6,4,2,6,8]Output: "_8_ 32"Explanation: Replace the substring "1":-1 maps to change[1]=8.Thus,"_1_ 32" becomes "_8_ 32"."832"is the largest number that can be created, so return it.
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.
To maximize the number, start mutating at the first position where the mapped digit is greater than the original, and keep mutating as long as the mapped digit is at least as large as the original. Stop at the first position where the mapped digit is less than the original.
classSolution {
public String maximumNumber(String num, int[] change) {
char[] ans = num.toCharArray();
boolean mut =false;
for (int i = 0; i < num.length(); ++i) {
int d = num.charAt(i) -'0', c = change[d];
if (!mut && c > d) { ans[i]= (char)(c +'0'); mut =true; }
elseif (mut && c >= d) ans[i]= (char)(c +'0');
elseif (mut && c < d) break;
}
returnnew String(ans);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funmaximumNumber(num: String, change: IntArray): String {
val ans = num.toCharArray()
var mut = falsefor (i in num.indices) {
val d = num[i] - '0'val c = change[d]
if (!mut && c > d) { ans[i] = (c + '0').toChar(); mut = true }
elseif (mut && c >= d) ans[i] = (c + '0').toChar()
elseif (mut && c < d) break }
return String(ans)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defmaximumNumber(self, num: str, change: list[int]) -> str:
ans = list(num)
mut =Falsefor i, ch in enumerate(num):
d = int(ch)
c = change[d]
ifnot mut and c > d:
ans[i] = str(c)
mut =Trueelif mut and c >= d:
ans[i] = str(c)
elif mut and c < d:
breakreturn''.join(ans)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
impl Solution {
pubfnmaximum_number(num: String, change: Vec<i32>) -> String {
letmut ans: Vec<u8>= num.bytes().collect();
letmut mutating =false;
for (i, &b) in num.as_bytes().iter().enumerate() {
let d = (b -b'0') asusize;
let c = change[d] asu8;
if!mutating && c > b -b'0' {
ans[i] = c +b'0';
mutating =true;
} elseif mutating && c >= b -b'0' {
ans[i] = c +b'0';
} elseif mutating && c < b -b'0' {
break;
}
}
String::from_utf8(ans).unwrap()
}
}