[LeetCode] Remove Digit From Number to Maximize Result

2259. Remove Digit From Number to Maximize Result

You are given a string number representing a positive integer and a character digit.

Return the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit occurs at least once in number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
string removeDigit(string number, char digit) {
int rm = -1;
for(int i = 0; i < number.length(); i++) {
if(number[i] != digit) continue;
if(i + 1 < number.length()) {
if(number[i+1] == digit) continue;
if(number[i+1] > digit) return number.substr(0, i) + number.substr(i+1);
else rm = i;
} else rm = i;
}
return number.substr(0, rm) + number.substr(rm+1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/01/PS/LeetCode/remove-digit-from-number-to-maximize-result/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.