You are given a string
number
representing a positive integer and a characterdigit
.Return the resulting string after removing exactly one occurrence of
digit
fromnumber
such that the value of the resulting string in decimal form is maximized. The test cases are generated such thatdigit
occurs at least once innumber
.
Removing the number ahead can increase the value of the digit next to the removed one is bigger than the removed one. From this, we can simply just loop the whole number and each time encounters the instructed digit, we check if the next digit is bigger or not, if so just remove it. else we just skip it to find the next one.
For edge case that we cannot remove any of the digits, we add a counter in it, the counter the total occurrences of the instructed digit, each time we encounter that digit we would deduct it by 1 when the counter equals 1, we would remove this remaining required digit.
class Solution {
public:
string removeDigit(string number, char digit) {
int count = 0;
for(int i = 0; i < number.length(); i++)if(digit == number[i])count++;
for(int i = 0; i < number.length()-1; i++){
if(number[i] < number[i + 1] && digit == number[i] || digit == number[i] && count == 1){
number.erase(i, 1);
return number;
}else if(digit == number[i] && count != 1){
count--;
}
}
number.erase(int(number.length())-1, 1);
return number;
}
};
1/5/2022