LeetCode 题解工作台

解码字母到整数映射

给你一个字符串 s ,它由数字( '0' - '9' )和 '#' 组成。我们希望按下述规则将 s 映射为一些小写英文字符: 字符( 'a' - 'i' )分别用( '1' - '9' )表示。 字符( 'j' - 'z' )分别用( '10#' - '26#' )表示。 返回映射之后形成的新字符串…

category

1

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们直接模拟即可。 遍历字符串 ,对于当前遍历到的下标 ,如果 $i + 2 < n$ 且 $s[i + 2]$ 为 `#`,则将 和 $s[i + 1]$ 组成的字符串转换为整数,加上 `a` 的 ASCII 码值减去 1,然后转换为字符,添加到结果数组中,并将 增加 3;否则,将 转换为整数,加上 `a` 的 ASCII 码值减去 1,然后转换为字符,添加到结果数组中,并将 增加 1。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 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 <= 1000
  • s[i] 只包含数字('0'-'9')和 '#' 字符。
  • s 是映射始终存在的有效字符串。
lightbulb

解题思路

方法一:模拟

我们直接模拟即可。

遍历字符串 ss,对于当前遍历到的下标 ii,如果 i+2<ni + 2 < ns[i+2]s[i + 2]#,则将 s[i]s[i]s[i+1]s[i + 1] 组成的字符串转换为整数,加上 a 的 ASCII 码值减去 1,然后转换为字符,添加到结果数组中,并将 ii 增加 3;否则,将 s[i]s[i] 转换为整数,加上 a 的 ASCII 码值减去 1,然后转换为字符,添加到结果数组中,并将 ii 增加 1。

最后将结果数组转换为字符串返回即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为字符串 ss 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
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)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

解码字母到整数映射题解:String-driven solution … | LeetCode #1309 简单