LeetCode 题解工作台
将所有数字用字符替换
给你一个下标从 0 开始的字符串 s ,它的 偶数 下标处为小写英文字母, 奇数 下标处为数字。 定义一个函数 shift(c, x) ,其中 c 是一个字符且 x 是一个数字,函数返回字母表中 c 后面第 x 个字符。 比方说, shift('a', 5) = 'f' 和 shift('x', 0…
1
题型
7
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
遍历字符串,对于奇数下标的字符,将其替换为前一个字符后移对应位数的字符。 最后返回替换后的字符串。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个下标从 0 开始的字符串 s ,它的 偶数 下标处为小写英文字母,奇数 下标处为数字。
定义一个函数 shift(c, x) ,其中 c 是一个字符且 x 是一个数字,函数返回字母表中 c 后面第 x 个字符。
- 比方说,
shift('a', 5) = 'f'和shift('x', 0) = 'x'。
对于每个 奇数 下标 i ,你需要将数字 s[i] 用 shift(s[i-1], s[i]) 替换。
请你替换所有数字以后,将字符串 s 返回。题目 保证 shift(s[i-1], s[i]) 不会超过 'z' 。
示例 1:
输入:s = "a1c1e1"
输出:"abcdef"
解释:数字被替换结果如下:
- s[1] -> shift('a',1) = 'b'
- s[3] -> shift('c',1) = 'd'
- s[5] -> shift('e',1) = 'f'
示例 2:
输入:s = "a1b2c3d4e"
输出:"abbdcfdhe"
解释:数字被替换结果如下:
- s[1] -> shift('a',1) = 'b'
- s[3] -> shift('b',2) = 'd'
- s[5] -> shift('c',3) = 'f'
- s[7] -> shift('d',4) = 'h'
提示:
1 <= s.length <= 100s只包含小写英文字母和数字。- 对所有 奇数 下标处的
i,满足shift(s[i-1], s[i]) <= 'z'。
解题思路
方法一:模拟
遍历字符串,对于奇数下标的字符,将其替换为前一个字符后移对应位数的字符。
最后返回替换后的字符串。
时间复杂度 ,其中 为字符串 的长度。忽略答案的空间消耗,空间复杂度 。
class Solution:
def replaceDigits(self, s: str) -> str:
s = list(s)
for i in range(1, len(s), 2):
s[i] = chr(ord(s[i - 1]) + int(s[i]))
return ''.join(s)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since each character is visited once and each shift operation is O(1). Space complexity is O(n) for constructing the new string with replaced characters. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask candidate to clarify how shift(c, x) works for letters and digits.
- question_mark
Check if the solution handles strings of maximum allowed length up to 100 characters.
- question_mark
Listen for reasoning about sequential processing versus precomputing shifts.
常见陷阱
外企场景- error
Misaligning indices and applying shifts to even indices instead of odd ones.
- error
Failing to convert digit characters to integer values before applying the shift.
- error
Modifying the original string in place and encountering unexpected results due to immutability.
进阶变体
外企场景- arrow_right_alt
Strings where digits may represent negative shifts or wrap-around alphabet positions.
- arrow_right_alt
Input strings containing only letters, testing edge behavior when no shifts are required.
- arrow_right_alt
Use of a different base alphabet or Unicode characters for shift operations.