LeetCode 题解工作台
字符串转换后的长度 I
给你一个字符串 s 和一个整数 t ,表示要执行的 转换 次数。每次 转换 需要根据以下规则替换字符串 s 中的每个字符: 如果字符是 'z' ,则将其替换为字符串 "ab" 。 否则,将其替换为字母表中的 下一个 字符。例如, 'a' 替换为 'b' , 'b' 替换为 'c' ,依此类推。 返回…
5
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示经过 次转换后,字母表中第 个字母的个数。初始时 为字符串 中字母表中第 个字母的个数。 每次转换后,字母表中第 个字母的个数可以通过以下方式计算:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个字符串 s 和一个整数 t,表示要执行的 转换 次数。每次 转换 需要根据以下规则替换字符串 s 中的每个字符:
- 如果字符是
'z',则将其替换为字符串"ab"。 - 否则,将其替换为字母表中的下一个字符。例如,
'a'替换为'b','b'替换为'c',依此类推。
返回 恰好 执行 t 次转换后得到的字符串的 长度。
由于答案可能非常大,返回其对 109 + 7 取余的结果。
示例 1:
输入: s = "abcyy", t = 2
输出: 7
解释:
- 第一次转换 (t = 1)
'a'变为'b''b'变为'c''c'变为'd''y'变为'z''y'变为'z'- 第一次转换后的字符串为:
"bcdzz"
- 第二次转换 (t = 2)
'b'变为'c''c'变为'd''d'变为'e''z'变为"ab"'z'变为"ab"- 第二次转换后的字符串为:
"cdeabab"
- 最终字符串长度:字符串为
"cdeabab",长度为 7 个字符。
示例 2:
输入: s = "azbk", t = 1
输出: 5
解释:
- 第一次转换 (t = 1)
'a'变为'b''z'变为"ab"'b'变为'c''k'变为'l'- 第一次转换后的字符串为:
"babcl"
- 最终字符串长度:字符串为
"babcl",长度为 5 个字符。
提示:
1 <= s.length <= 105s仅由小写英文字母组成。1 <= t <= 105
解题思路
方法一:递推
我们定义 表示经过 次转换后,字母表中第 个字母的个数。初始时 为字符串 中字母表中第 个字母的个数。
每次转换后,字母表中第 个字母的个数可以通过以下方式计算:
答案为 。
由于答案可能非常大,我们需要对 取模。
时间复杂度 ,空间复杂度 ,其中 为字母表的大小。
class Solution:
def lengthAfterTransformations(self, s: str, t: int) -> int:
f = [[0] * 26 for _ in range(t + 1)]
for c in s:
f[0][ord(c) - ord("a")] += 1
for i in range(1, t + 1):
f[i][0] = f[i - 1][25]
f[i][1] = f[i - 1][0] + f[i - 1][25]
for j in range(2, 26):
f[i][j] = f[i - 1][j - 1]
mod = 10**9 + 7
return sum(f[t]) % mod
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n + t|Σ|) where n is the initial string length and |Σ| is the alphabet size, since each transformation updates character counts. Space complexity is O(|Σ|) for storing frequency counts of all lowercase letters. |
| 空间 | O( |
面试官常问的追问
外企场景- question_mark
Notice how naive string reconstruction fails for large t due to exponential growth.
- question_mark
Tracking frequencies instead of actual strings is key for optimal performance.
- question_mark
State transition dynamic programming is expected; watch for off-by-one or modulo errors.
常见陷阱
外企场景- error
Attempting to build the full string at each transformation, causing memory overflow.
- error
Forgetting to apply modulo after each addition, leading to integer overflow.
- error
Mismanaging frequency updates and double-counting characters in transitions.
进阶变体
外企场景- arrow_right_alt
Return the actual transformed string instead of its length for small t.
- arrow_right_alt
Allow custom transformation rules defined per character.
- arrow_right_alt
Compute the maximum character frequency after t transformations rather than total length.