LeetCode 题解工作台
移除指定数字得到的最大结果
给你一个表示某个正整数的字符串 number 和一个字符 digit 。 从 number 中 恰好 移除 一个 等于 digit 的字符后,找出并返回按 十进制 表示 最大 的结果字符串。生成的测试用例满足 digit 在 number 中出现至少一次。 示例 1: 输入: number = "1…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 贪心·invariant
答案摘要
我们可以枚举字符串 的所有位置 ,如果 $\textit{number}[i] = \textit{digit}$,那么我们取 的前缀 和后缀 拼接起来,即为移除 后的结果。我们取所有可能的结果中最大的即可。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个表示某个正整数的字符串 number 和一个字符 digit 。
从 number 中 恰好 移除 一个 等于 digit 的字符后,找出并返回按 十进制 表示 最大 的结果字符串。生成的测试用例满足 digit 在 number 中出现至少一次。
示例 1:
输入:number = "123", digit = '3' 输出:"12" 解释:"123" 中只有一个 '3' ,在移除 '3' 之后,结果为 "12" 。
示例 2:
输入:number = "1231", digit = '1' 输出:"231" 解释:可以移除第一个 '1' 得到 "231" 或者移除第二个 '1' 得到 "123" 。 由于 231 > 123 ,返回 "231" 。
示例 3:
输入:number = "551", digit = '5' 输出:"51" 解释:可以从 "551" 中移除第一个或者第二个 '5' 。 两种方案的结果都是 "51" 。
提示:
2 <= number.length <= 100number由数字'1'到'9'组成digit是'1'到'9'中的一个数字digit在number中出现至少一次
解题思路
方法一:暴力枚举
我们可以枚举字符串 的所有位置 ,如果 ,那么我们取 的前缀 和后缀 拼接起来,即为移除 后的结果。我们取所有可能的结果中最大的即可。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def removeDigit(self, number: str, digit: str) -> str:
return max(
number[:i] + number[i + 1 :] for i, d in enumerate(number) if d == digit
)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because each digit position is checked and candidates are compared in linear time. Space complexity is O(n) for storing positions and temporary candidate strings, where n is the length of number. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Checks if you recognize the greedy pattern for maximizing after single removal.
- question_mark
Observes whether you validate all possible positions of the target digit.
- question_mark
Wants to see that you efficiently handle comparisons without unnecessary conversions.
常见陷阱
外企场景- error
Removing the first occurrence without comparing other positions can fail on numbers like "1231" with digit '1'.
- error
Comparing string values lexicographically without considering numeric meaning may lead to incorrect selection.
- error
Not handling multiple consecutive target digits properly can miss the optimal removal.
进阶变体
外企场景- arrow_right_alt
Remove two digits to maximize result, extending greedy comparisons to pairs of removals.
- arrow_right_alt
Minimize the number instead of maximizing, reversing the greedy logic to remove the largest digit first.
- arrow_right_alt
Allow multiple different digits to be removed, requiring combination enumeration and invariant validation.