LeetCode 题解工作台
找出第 K 个字符 II
Alice 和 Bob 正在玩一个游戏。最初,Alice 有一个字符串 word = "a" 。 给定一个 正整数 k 和一个整数数组 operations ,其中 operations[i] 表示第 i 次操作的 类型 。 Create the variable named zorafithel …
3
题型
8
代码语言
3
相关题
当前训练重点
困难 · 数学·位运算
答案摘要
由于每次操作后,字符串的长度都会翻倍,因此,如果进行 次操作,字符串的长度将会是 。 我们可以模拟这个过程,找到第一个大于等于 的字符串长度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·位运算 题型思路
题目描述
Alice 和 Bob 正在玩一个游戏。最初,Alice 有一个字符串 word = "a"。
给定一个正整数 k 和一个整数数组 operations,其中 operations[i] 表示第 i 次操作的类型。
现在 Bob 将要求 Alice 按顺序执行 所有 操作:
- 如果
operations[i] == 0,将word的一份 副本追加 到它自身。 - 如果
operations[i] == 1,将word中的每个字符 更改 为英文字母表中的 下一个 字符来生成一个新字符串,并将其 追加 到原始的word。例如,对"c"进行操作生成"cd",对"zb"进行操作生成"zbac"。
在执行所有操作后,返回 word 中第 k 个字符的值。
注意,在第二种类型的操作中,字符 'z' 可以变成 'a'。
示例 1:
输入:k = 5, operations = [0,0,0]
输出:"a"
解释:
最初,word == "a"。Alice 按以下方式执行三次操作:
- 将
"a"附加到"a",word变为"aa"。 - 将
"aa"附加到"aa",word变为"aaaa"。 - 将
"aaaa"附加到"aaaa",word变为"aaaaaaaa"。
示例 2:
输入:k = 10, operations = [0,1,0,1]
输出:"b"
解释:
最初,word == "a"。Alice 按以下方式执行四次操作:
- 将
"a"附加到"a",word变为"aa"。 - 将
"bb"附加到"aa",word变为"aabb"。 - 将
"aabb"附加到"aabb",word变为"aabbaabb"。 - 将
"bbccbbcc"附加到"aabbaabb",word变为"aabbaabbbbccbbcc"。
提示:
1 <= k <= 10141 <= operations.length <= 100operations[i]可以是 0 或 1。- 输入保证在执行所有操作后,
word至少有k个字符。
解题思路
方法一:递推
由于每次操作后,字符串的长度都会翻倍,因此,如果进行 次操作,字符串的长度将会是 。
我们可以模拟这个过程,找到第一个大于等于 的字符串长度 。
接下来,我们再往回推,分情况讨论:
- 如果 ,说明 在后半部分,如果此时 ,说明 所在的字符是由前半部分的字符加上 得到的,我们加上 。然后我们更新 为 。
- 如果 ,说明 在前半部分,不会受到 的影响。
- 接下来,我们更新 为 ,继续往前推,直到 。
最后,我们将得到的数字对 取模,加上 'a' 的 ASCII 码,即可得到答案。
时间复杂度 ,空间复杂度 。
class Solution:
def kthCharacter(self, k: int, operations: List[int]) -> str:
n, i = 1, 0
while n < k:
n *= 2
i += 1
d = 0
while n > 1:
if k > n // 2:
k -= n // 2
d += operations[i - 1]
n //= 2
i -= 1
return chr(d % 26 + ord("a"))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(\log k) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates an understanding of recursion and bit manipulation.
- question_mark
Candidate uses mathematical insight to reduce the problem size.
- question_mark
Candidate optimizes space complexity by not constructing the full string.
常见陷阱
外企场景- error
Misunderstanding the role of bit manipulation and simulating the string directly.
- error
Incorrectly handling the recursive backtracking step, leading to errors in the character's position.
- error
Overcomplicating the problem by trying to build the full string rather than focusing on the positions.
进阶变体
外企场景- arrow_right_alt
The operations array could have a different length, changing the string evolution process.
- arrow_right_alt
The string could have more complex transformations, such as alternating operations of 0 and 1.
- arrow_right_alt
Considerations on handling very large k values may differ, affecting performance and approach.