LeetCode 题解工作台

具有给定数值的最小字符串

小写字符 的 数值 是它在字母表中的位置(从 1 开始),因此 a 的数值为 1 , b 的数值为 2 , c 的数值为 3 ,以此类推。 字符串由若干小写字符组成, 字符串的数值 为各字符的数值之和。例如,字符串 "abe" 的数值等于 1 + 2 + 5 = 8 。 给你两个整数 n 和 k 。…

category

2

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

我们先将字符串的每个字符都初始化为 `'a'`,此时剩余的数值为 。 接着从后往前遍历字符串,每次贪心地将当前位置的字符替换为能够使得剩余的数字最小的字符 `'z'`,直到剩余的数字不超过 。最后将剩余的数字加到我们遍历到的位置上即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

小写字符 数值 是它在字母表中的位置(从 1 开始),因此 a 的数值为 1b 的数值为 2c 的数值为 3 ,以此类推。

字符串由若干小写字符组成,字符串的数值 为各字符的数值之和。例如,字符串 "abe" 的数值等于 1 + 2 + 5 = 8

给你两个整数 nk 。返回 长度 等于 n数值 等于 k字典序最小 的字符串。

注意,如果字符串 x 在字典排序中位于 y 之前,就认为 x 字典序比 y 小,有以下两种情况:

  • xy 的一个前缀;
  • 如果 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 <= 105
  • n <= k <= 26 * n
lightbulb

解题思路

方法一:贪心

我们先将字符串的每个字符都初始化为 'a',此时剩余的数值为 d=knd=k-n

接着从后往前遍历字符串,每次贪心地将当前位置的字符替换为能够使得剩余的数字最小的字符 'z',直到剩余的数字不超过 2525。最后将剩余的数字加到我们遍历到的位置上即可。

时间复杂度 O(n)O(n),其中 nn 为字符串的长度。忽略答案的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
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)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

具有给定数值的最小字符串题解:贪心·invariant | LeetCode #1663 中等