答:不可能在删除后只得到 00,因为题目保证 num 不含前导零,如果有多个 0,那么 0 的左侧必然有非 0 数字。
[sol-Python3]
1 2 3 4 5 6 7 8 9 10
classSolution: defminimumOperations(self, num: str) -> int: n = len(num) deff(tail: str) -> int: i = num.rfind(tail[1]) if i < 0: return n i = num.rfind(tail[0], 0, i) # 写成 num[:i].rfind(tail[0]) 会产生额外的切片空间 if i < 0: return n return n - i - 2 returnmin(n - ('0'in num), f("00"), f("25"), f("50"), f("75"))
publicintminimumOperations(String num) { ans = num.length(); if (num.contains("0")) ans--; f(num, "00"); f(num, "25"); f(num, "50"); f(num, "75"); return ans; }
privatevoidf(String num, String tail) { intn= num.length(); inti= num.lastIndexOf(tail.charAt(1)); if (i < 0) return; i = num.lastIndexOf(tail.charAt(0), i - 1); if (i < 0) return; ans = Math.min(ans, n - i - 2); } }
[sol-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: intminimumOperations(string num){ int n = num.length(); auto f = [&](string tail) { int i = num.rfind(tail[1]); if (i == string::npos || i == 0) return n; i = num.rfind(tail[0], i - 1); if (i == string::npos) return n; return n - i - 2; }; returnmin({n - (num.find('0') != string::npos), f("00"), f("25"), f("50"), f("75")}); } };