[LeetCode] Minimum Operations to Make a Special Number

2844. Minimum Operations to Make a Special Number

You are given a 0-indexed string num representing a non-negative integer.

In one operation, you can pick any digit of num and delete it. Note that if you delete all the digits of num, num becomes 0.

Return the minimum number of operations required to make num special.

An integer x is considered special if it is divisible by 25.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int helper(string& s, string p) {
int res = 0;
for(int i = s.length() - 1, j = 1; i >= 0; i--) {
if(s[i] == p[j]) j -= 1;
else res += 1;
if(j == -1) return res;
if(i == 0 and p == "00" and j == 0) return s.length() - 1;
}
return s.length();
}
public:
int minimumOperations(string num) {
int res = num.length();
res = min(res, helper(num,"00"));
res = min(res, helper(num,"25"));
res = min(res, helper(num,"50"));
res = min(res, helper(num,"75"));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/09/03/PS/LeetCode/minimum-operations-to-make-a-special-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.