-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2259-Remove-Digit-From-Number-to-Maximize-Result.cpp
59 lines (54 loc) · 1.44 KB
/
2259-Remove-Digit-From-Number-to-Maximize-Result.cpp
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
public:
string removeDigit(string number, char digit) {
int freq = 0;
for(auto c: number){
if(c == digit) {
freq++;
if(freq > 1) break;
}
}
if(freq == 1){
int i = 0;
for(auto c: number){
if(c == digit){
number.erase(number.begin() + i);
return number;
}
i++;
}
}
int lastIdx = 0;
for(int i = 0; i < number.size() - 1; i++){
if(number[i] == digit && digit < number[i+1]){
number.erase(number.begin() + i);
return number;
}
if(number[i] == digit){
lastIdx = i;
}
}
if(number[number.size()-1] == digit){
number.erase(number.begin() + (number.size() - 1 ));
return number;
}else{
number.erase(number.begin() + lastIdx);
return number;
}
return "";
}
};
// Another solution
class Solution {
public:
string removeDigit(string number, char digit) {
string res = "";
for(int i=0; i<number.size(); i++){
if(number[i] == digit){
string temp = number.substr(0, i) + number.substr(i+1);
res = max(res, temp);
}
}
return res;
}
};