LeetCode 题解工作台
具有给定数值的最小字符串
小写字符 的 数值 是它在字母表中的位置(从 1 开始),因此 a 的数值为 1 , b 的数值为 2 , c 的数值为 3 ,以此类推。 字符串由若干小写字符组成, 字符串的数值 为各字符的数值之和。例如,字符串 "abe" 的数值等于 1 + 2 + 5 = 8 。 给你两个整数 n 和 k 。…
2
题型
4
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们先将字符串的每个字符都初始化为 `'a'`,此时剩余的数值为 。 接着从后往前遍历字符串,每次贪心地将当前位置的字符替换为能够使得剩余的数字最小的字符 `'z'`,直到剩余的数字不超过 。最后将剩余的数字加到我们遍历到的位置上即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
小写字符 的 数值 是它在字母表中的位置(从 1 开始),因此 a 的数值为 1 ,b 的数值为 2 ,c 的数值为 3 ,以此类推。
字符串由若干小写字符组成,字符串的数值 为各字符的数值之和。例如,字符串 "abe" 的数值等于 1 + 2 + 5 = 8 。
给你两个整数 n 和 k 。返回 长度 等于 n 且 数值 等于 k 的 字典序最小 的字符串。
注意,如果字符串 x 在字典排序中位于 y 之前,就认为 x 字典序比 y 小,有以下两种情况:
x是y的一个前缀;- 如果
i是x[i] != y[i]的第一个位置,且x[i]在字母表中的位置比y[i]靠前。
示例 1:
输入:n = 3, k = 27 输出:"aay" 解释:字符串的数值为 1 + 1 + 25 = 27,它是数值满足要求且长度等于 3 字典序最小的字符串。
示例 2:
输入:n = 5, k = 73 输出:"aaszz"
提示:
1 <= n <= 105n <= k <= 26 * n
解题思路
方法一:贪心
我们先将字符串的每个字符都初始化为 'a',此时剩余的数值为 。
接着从后往前遍历字符串,每次贪心地将当前位置的字符替换为能够使得剩余的数字最小的字符 'z',直到剩余的数字不超过 。最后将剩余的数字加到我们遍历到的位置上即可。
时间复杂度 ,其中 为字符串的长度。忽略答案的空间消耗,空间复杂度 。
class Solution:
def getSmallestString(self, n: int, k: int) -> str:
ans = ['a'] * n
i, d = n - 1, k - n
while d > 25:
ans[i] = 'z'
d -= 25
i -= 1
ans[i] = chr(ord(ans[i]) + d)
return ''.join(ans)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates an understanding of greedy algorithms.
- question_mark
The candidate can apply greedy choices within the constraints of the problem.
- question_mark
The candidate addresses edge cases and can explain the invariant validation process.
常见陷阱
外企场景- error
Failing to account for the remaining sum after each greedy step.
- error
Not considering the possibility of overshooting the required sum when selecting the largest valid character.
- error
Misunderstanding the lexicographical order when adjusting the string’s characters.
进阶变体
外企场景- arrow_right_alt
Minimize the string length while still achieving a numeric sum equal to k.
- arrow_right_alt
Extend the problem to handle uppercase letters as well.
- arrow_right_alt
Solve the problem for multiple queries simultaneously, optimizing for performance.