1. 解题思路
思路来说这道题就是比较简单的一个贪婪算法,从头开始考察每一个字符串,给其分配距离不大于k的最小的字符即可。
2. 代码实现
给出python代码实现如下:
class Solution:
def getSmallestString(self, s: str, k: int) -> str:
def fn(ch1, ch2):
d = (ord(ch1) - ord(ch2)) % 26
return min(d, 26-d)
ans = ""
for ch in s:
for c in string.ascii_lowercase:
d = fn(ch, c)
if d <= k:
ans += c
k -= d
break
return ans
提交代码评测得到:耗时65ms,占用内存16.6MB。
LeetCode3106:使用贪心算法求在约束下最小字典序字符串
本文介绍了如何通过贪婪策略解决LeetCode问题3106,给定字符串s和整数k,找到在不超过k次操作后能得到的字典序最小字符串。作者提供了Python代码实现并分析了时间复杂度和内存占用情况。

569

被折叠的 条评论
为什么被折叠?



