LeetCode 题解工作台
找出第 K 个字符 I
Alice 和 Bob 正在玩一个游戏。最初,Alice 有一个字符串 word = "a" 。 给定一个 正整数 k 。 现在 Bob 会要求 Alice 执行以下操作 无限次 : 将 word 中的每个字符 更改 为英文字母表中的 下一个 字符来生成一个新字符串,并将其 追加 到原始的 word…
4
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数学·位运算
答案摘要
我们可以使用一个数组 来存储每次操作后的字符串,当 的长度小于 时,我们不断地对 进行操作。 最后返回 $\textit{word}[k - 1]$ 即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·位运算 题型思路
题目描述
Alice 和 Bob 正在玩一个游戏。最初,Alice 有一个字符串 word = "a"。
给定一个正整数 k。
现在 Bob 会要求 Alice 执行以下操作 无限次 :
- 将
word中的每个字符 更改 为英文字母表中的 下一个 字符来生成一个新字符串,并将其 追加 到原始的word。
例如,对 "c" 进行操作生成 "cd",对 "zb" 进行操作生成 "zbac"。
在执行足够多的操作后, word 中 至少 存在 k 个字符,此时返回 word 中第 k 个字符的值。
示例 1:
输入:k = 5
输出:"b"
解释:
最初,word = "a"。需要进行三次操作:
- 生成的字符串是
"b",word变为"ab"。 - 生成的字符串是
"bc",word变为"abbc"。 - 生成的字符串是
"bccd",word变为"abbcbccd"。
示例 2:
输入:k = 10
输出:"c"
提示:
1 <= k <= 500
解题思路
方法一:模拟
我们可以使用一个数组 来存储每次操作后的字符串,当 的长度小于 时,我们不断地对 进行操作。
最后返回 即可。
时间复杂度 ,空间复杂度 。其中 为输入参数。
class Solution:
def kthCharacter(self, k: int) -> str:
word = [0]
while len(word) < k:
word.extend([(x + 1) % 26 for x in word])
return chr(ord("a") + word[k - 1])
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(log k) because each step halves the search space for the K-th character. Space complexity is O(1) since we avoid storing the full string and only track indices and lengths. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Candidate immediately identifies the string doubling and letter increment pattern.
- question_mark
Candidate proposes a solution without constructing the entire string.
- question_mark
Candidate correctly applies bit manipulation or recursion to locate position k.
常见陷阱
外企场景- error
Attempting to build the entire string, which exceeds reasonable space limits.
- error
Misaligning the index during recursion or bit tracing.
- error
Confusing the letter sequence or off-by-one errors when converting indices to characters.
进阶变体
外企场景- arrow_right_alt
Determine the K-th character when the starting string is a different single letter.
- arrow_right_alt
Generalize the problem to a custom alphabet or longer repeating patterns.
- arrow_right_alt
Find the last character after n doubling operations instead of a specific K-th position.