LeetCode 题解工作台
解码字母到整数映射
给你一个字符串 s ,它由数字( '0' - '9' )和 '#' 组成。我们希望按下述规则将 s 映射为一些小写英文字符: 字符( 'a' - 'i' )分别用( '1' - '9' )表示。 字符( 'j' - 'z' )分别用( '10#' - '26#' )表示。 返回映射之后形成的新字符串…
1
题型
7
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
我们直接模拟即可。 遍历字符串 ,对于当前遍历到的下标 ,如果 $i + 2 < n$ 且 $s[i + 2]$ 为 `#`,则将 和 $s[i + 1]$ 组成的字符串转换为整数,加上 `a` 的 ASCII 码值减去 1,然后转换为字符,添加到结果数组中,并将 增加 3;否则,将 转换为整数,加上 `a` 的 ASCII 码值减去 1,然后转换为字符,添加到结果数组中,并将 增加 1。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个字符串 s,它由数字('0' - '9')和 '#' 组成。我们希望按下述规则将 s 映射为一些小写英文字符:
- 字符(
'a'-'i')分别用('1'-'9')表示。 - 字符(
'j'-'z')分别用('10#'-'26#')表示。
返回映射之后形成的新字符串。
题目数据保证映射始终唯一。
示例 1:
输入:s = "10#11#12" 输出:"jkab" 解释:"j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2".
示例 2:
输入:s = "1326#" 输出:"acz"
提示:
1 <= s.length <= 1000s[i]只包含数字('0'-'9')和'#'字符。s是映射始终存在的有效字符串。
解题思路
方法一:模拟
我们直接模拟即可。
遍历字符串 ,对于当前遍历到的下标 ,如果 且 为 #,则将 和 组成的字符串转换为整数,加上 a 的 ASCII 码值减去 1,然后转换为字符,添加到结果数组中,并将 增加 3;否则,将 转换为整数,加上 a 的 ASCII 码值减去 1,然后转换为字符,添加到结果数组中,并将 增加 1。
最后将结果数组转换为字符串返回即可。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def freqAlphabets(self, s: str) -> str:
ans = []
i, n = 0, len(s)
while i < n:
if i + 2 < n and s[i + 2] == "#":
ans.append(chr(int(s[i : i + 2]) + ord("a") - 1))
i += 3
else:
ans.append(chr(int(s[i]) + ord("a") - 1))
i += 1
return "".join(ans)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate scans the string from right to left.
- question_mark
Candidate correctly handles '#' for two-digit numbers.
- question_mark
Candidate avoids unnecessary string reversals, constructing the result efficiently.
常见陷阱
外企场景- error
Forgetting to skip characters after decoding two-digit numbers with '#'.
- error
Misinterpreting the '#' symbol, either as part of a digit or skipping it.
- error
Inefficiently reversing the string after decoding, instead of building it from right to left.
进阶变体
外企场景- arrow_right_alt
Handling strings with only single-digit characters.
- arrow_right_alt
Adapting the solution to work with uppercase letters instead of lowercase.
- arrow_right_alt
Dealing with larger strings and optimizing for performance.