LeetCode 题解工作台
满足距离约束且字典序最小的字符串
给你一个字符串 s 和一个整数 k 。 定义函数 distance(s 1 , s 2 ) ,用于衡量两个长度为 n 的字符串 s 1 和 s 2 之间的距离,即: 字符 'a' 到 'z' 按 循环 顺序排列,对于区间 [0, n - 1] 中的 i ,计算所有「 s 1 [i] 和 s 2 [i…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们可以遍历字符串 的每个位置,对于每个位置,我们枚举所有小于当前字符的字符,计算改变到这个字符的代价 ,如果 $d \leq k$,我们就将当前位置的字符改为这个字符,并将 减去 ,然后结束枚举,继续遍历下一个位置。 遍历结束后,我们就得到了一个满足条件的字符串。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个字符串 s 和一个整数 k 。
定义函数 distance(s1, s2) ,用于衡量两个长度为 n 的字符串 s1 和 s2 之间的距离,即:
- 字符
'a'到'z'按 循环 顺序排列,对于区间[0, n - 1]中的i,计算所有「s1[i]和s2[i]之间 最小距离」的 和 。
例如,distance("ab", "cd") == 4 ,且 distance("a", "z") == 1 。
你可以对字符串 s 执行 任意次 操作。在每次操作中,可以将 s 中的一个字母 改变 为 任意 其他小写英文字母。
返回一个字符串,表示在执行一些操作后你可以得到的 字典序最小 的字符串 t ,且满足 distance(s, t) <= k 。
示例 1:
输入:s = "zbbz", k = 3 输出:"aaaz" 解释:在这个例子中,可以执行以下操作: 将 s[0] 改为 'a' ,s 变为 "abbz" 。 将 s[1] 改为 'a' ,s 变为 "aabz" 。 将 s[2] 改为 'a' ,s 变为 "aaaz" 。 "zbbz" 和 "aaaz" 之间的距离等于 k = 3 。 可以证明 "aaaz" 是在任意次操作后能够得到的字典序最小的字符串。 因此,答案是 "aaaz" 。
示例 2:
输入:s = "xaxcd", k = 4 输出:"aawcd" 解释:在这个例子中,可以执行以下操作: 将 s[0] 改为 'a' ,s 变为 "aaxcd" 。 将 s[2] 改为 'w' ,s 变为 "aawcd" 。 "xaxcd" 和 "aawcd" 之间的距离等于 k = 4 。 可以证明 "aawcd" 是在任意次操作后能够得到的字典序最小的字符串。 因此,答案是 "aawcd" 。
示例 3:
输入:s = "lol", k = 0 输出:"lol" 解释:在这个例子中,k = 0,更改任何字符都会使得距离大于 0 。 因此,答案是 "lol" 。
提示:
1 <= s.length <= 1000 <= k <= 2000s只包含小写英文字母。
解题思路
方法一:枚举
我们可以遍历字符串 的每个位置,对于每个位置,我们枚举所有小于当前字符的字符,计算改变到这个字符的代价 ,如果 ,我们就将当前位置的字符改为这个字符,并将 减去 ,然后结束枚举,继续遍历下一个位置。
遍历结束后,我们就得到了一个满足条件的字符串。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度;而 是字符集的大小,本题中 。
class Solution:
def getSmallestString(self, s: str, k: int) -> str:
cs = list(s)
for i, c1 in enumerate(s):
for c2 in ascii_lowercase:
if c2 >= c1:
break
d = min(ord(c1) - ord(c2), 26 - ord(c1) + ord(c2))
if d <= k:
cs[i] = c2
k -= d
break
return "".join(cs)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The problem can be solved greedily with careful validation of the operations.
- question_mark
Watch for edge cases like when k equals zero, where no operations can be performed.
- question_mark
Candidates should be able to explain the trade-off of minimizing the string while adhering to the distance constraint.
常见陷阱
外企场景- error
Not handling the case where k equals zero and no changes can be made.
- error
Misunderstanding the distance calculation or failing to properly track the allowed distance.
- error
Not considering the edge case where the string is already the lexicographically smallest, requiring no operations.
进阶变体
外企场景- arrow_right_alt
What if the operations are unlimited? This would simplify the problem significantly.
- arrow_right_alt
Consider modifying the string to a fixed target rather than minimizing it.
- arrow_right_alt
What if we were allowed to change only specific positions in the string rather than all characters?