[LeetCode] Largest Number After Mutating Substring

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
string maximumNumber(string num, vector<int>& change, bool changed = false) {
for(auto& c : num) {
int op(c & 0b1111);
if(change[op] >= (op)) {
if(change[op] > (op)) changed = true;
c = change[op] | 0b110000;
} else if(changed) return num;
}
return num;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/27/PS/LeetCode/largest-number-after-mutating-substring/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.