LeetCode 题解工作台
子字符串突变后可能得到的最大整数
给你一个字符串 num ,该字符串表示一个大整数。另给你一个长度为 10 且 下标从 0 开始 的整数数组 change ,该数组将 0-9 中的每个数字映射到另一个数字。更规范的说法是,数字 d 映射为数字 change[d] 。 你可以选择 突变 num 的任一子字符串。 突变 子字符串意味着将…
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
根据题目描述,我们可以从字符串的高位开始,贪心的进行连续的替换操作,直到遇到一个比当前位数字小的数字为止。 我们先将字符串 转换为字符数组 ,用一个变量 记录是否已经发生过变化,初始时 $\textit{changed} = \text{false}$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个字符串 num ,该字符串表示一个大整数。另给你一个长度为 10 且 下标从 0 开始 的整数数组 change ,该数组将 0-9 中的每个数字映射到另一个数字。更规范的说法是,数字 d 映射为数字 change[d] 。
你可以选择 突变 num 的任一子字符串。突变 子字符串意味着将每位数字 num[i] 替换为该数字在 change 中的映射(也就是说,将 num[i] 替换为 change[num[i]])。
请你找出在对 num 的任一子字符串执行突变操作(也可以不执行)后,可能得到的 最大整数 ,并用字符串表示返回。
子字符串 是字符串中的一个连续序列。
示例 1:
输入:num = "132", change = [9,8,5,0,3,6,4,2,6,8] 输出:"832" 解释:替换子字符串 "1": - 1 映射为 change[1] = 8 。 因此 "132" 变为 "832" 。 "832" 是可以构造的最大整数,所以返回它的字符串表示。
示例 2:
输入:num = "021", change = [9,4,3,5,7,2,1,9,0,6] 输出:"934" 解释:替换子字符串 "021": - 0 映射为 change[0] = 9 。 - 2 映射为 change[2] = 3 。 - 1 映射为 change[1] = 4 。 因此,"021" 变为 "934" 。 "934" 是可以构造的最大整数,所以返回它的字符串表示。
示例 3:
输入:num = "5", change = [1,4,7,5,3,2,5,6,9,4] 输出:"5" 解释:"5" 已经是可以构造的最大整数,所以返回它的字符串表示。
提示:
1 <= num.length <= 105num仅由数字0-9组成change.length == 100 <= change[d] <= 9
解题思路
方法一:贪心
根据题目描述,我们可以从字符串的高位开始,贪心的进行连续的替换操作,直到遇到一个比当前位数字小的数字为止。
我们先将字符串 转换为字符数组 ,用一个变量 记录是否已经发生过变化,初始时 。
然后我们遍历字符数组 ,对于每个字符 ,我们将其转换为数字 ,如果已经发生过变化且 ,则说明我们不能再继续变化,直接退出循环;否则,如果 ,则说明我们可以将 替换为 ,此时我们将 ,并将 替换为 。
最后我们将字符数组 转换为字符串并返回即可。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def maximumNumber(self, num: str, change: List[int]) -> str:
s = list(num)
changed = False
for i, c in enumerate(s):
d = str(change[int(c)])
if changed and d < c:
break
if d > c:
changed = True
s[i] = d
return "".join(s)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Evaluating the candidate's ability to apply a greedy strategy in a non-trivial mutation problem.
- question_mark
Checking for understanding of early stopping and its importance in optimizing the solution.
- question_mark
Assessing the candidate's grasp of the pattern behind the greedy approach and its validation.
常见陷阱
外企场景- error
Failing to stop mutating when the result becomes smaller than the original number.
- error
Not recognizing that changing digits in the middle of the number can lead to smaller results if not carefully handled.
- error
Mutating a digit even when it doesn’t improve the value, leading to unnecessary changes.
进阶变体
外企场景- arrow_right_alt
Allowing multiple substrings to mutate instead of just one.
- arrow_right_alt
Different variations of the mapping where some digits map to the same value.
- arrow_right_alt
Adding conditions like not allowing leading zeros after mutation.