To solve this problem, we need to determine the minimum number of deletions required to make a given number (as a string) divisible by 25. A number is divisible by 25 if its last two digits form one of the pairs: 00, 25, 50, or 75.
Approach
- Identify Valid Suffixes: The valid suffixes for divisibility by 25 are "00", "25", "50", and "75".
- Check Each Suffix: For each valid suffix, we need to find the rightmost occurrence of the second digit of the suffix, then find the rightmost occurrence of the first digit of the suffix before the second digit.
- Calculate Deletions: For each valid pair of positions (first digit, second digit), compute the number of deletions needed to keep these digits as the last two digits of the resulting number. The number of deletions is the original length of the string minus the length of the resulting number (which is the position of the first digit plus 2, since we keep all characters up to the first digit and the second digit).
- Find Minimum Deletions: The minimum number of deletions across all valid suffixes is the answer. If no valid suffix is found, return -1.
Solution Code
s = input().strip()
targets = [('0', '0'), ('2', '5'), ('5', '0'), ('7', '5')]
min_ops = float('inf')
for a, b in targets:
idx_b = s.rfind(b)
if idx_b == -1:
continue
idx_a = s[:idx_b].rfind(a)
if idx_a == -1:
continue
ops = len(s) - (idx_a + 2)
if ops < min_ops:
min_ops = ops
print(min_ops if min_ops != float('inf') else -1)
Explanation
- Valid Suffix Check: For each suffix (like "25"), we first find the rightmost occurrence of the second digit ("5"). Then, we find the rightmost occurrence of the first digit ("2") before this position.
- Deletion Calculation: The number of deletions is calculated as the original length of the string minus the length of the resulting number (positions up to the first digit plus the second digit). This gives the minimum deletions needed for that suffix.
- Result: The minimum value from all valid suffix calculations is the answer, or -1 if no valid suffix exists.
This approach efficiently checks all possible valid suffixes and computes the minimum deletions required, ensuring optimal performance even for longer strings. The use of rfind helps in quickly finding the rightmost positions, making the solution both effective and efficient.


作者声明:本文包含人工智能生成内容。