2259. Remove Digit From Number to Maximize Result

2259. Remove Digit From Number to Maximize Result

Question

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.

Solution

按顺序比较当前等于digit的字符及下一个字符,如果当前字符小于后面的字符,则移除它是最优解。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public String removeDigit(String number, char digit) {
boolean found = false;
int equal = 0;
for(int i = 0; i < number.length(); i++){
if(number.charAt(i) == digit)equal++;
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < number.length() - 1; i++){
if(number.charAt(i) == digit && !found){
if(number.charAt(i) < number.charAt(i+1)){
found = true;
}
else{
equal--;
if(equal > 0){
sb.append(number.charAt(i));
}
else{
found = true;
}
}
}
else{
sb.append(number.charAt(i));
}
}

if(found) sb.append(number.charAt(number.length()-1));
return sb.toString();
}
}
Author

Xander

Posted on

2023-05-11

Updated on

2023-05-11

Licensed under

Comments