LeetCode 题解工作台

解密消息

给你字符串 key 和 message ,分别表示一个加密密钥和一段加密消息。解密 message 的步骤如下: 使用 key 中 26 个英文小写字母第一次出现的顺序作为替换表中的字母 顺序 。 将替换表与普通英文字母表对齐,形成对照表。 按照对照表 替换 message 中的每个字母。 空格 '…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·表·结合·string

bolt

答案摘要

我们可以使用数组或哈希表 存储对照表,然后遍历 `message` 中的每个字符,将其替换为对应的字符即可。 时间复杂度 $O(m + n)$,空间复杂度 。其中 和 分别为 `key` 和 `message` 的长度;而 为字符集大小。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你字符串 keymessage ,分别表示一个加密密钥和一段加密消息。解密 message 的步骤如下:

  1. 使用 key 中 26 个英文小写字母第一次出现的顺序作为替换表中的字母 顺序
  2. 将替换表与普通英文字母表对齐,形成对照表。
  3. 按照对照表 替换 message 中的每个字母。
  4. 空格 ' ' 保持不变。
  • 例如,key = "happy boy"(实际的加密密钥会包含字母表中每个字母 至少一次),据此,可以得到部分对照表('h' -> 'a''a' -> 'b''p' -> 'c''y' -> 'd''b' -> 'e''o' -> 'f')。

返回解密后的消息。

 

示例 1:

输入:key = "the quick brown fox jumps over the lazy dog", message = "vkbs bs t suepuv"
输出:"this is a secret"
解释:对照表如上图所示。
提取 "the quick brown fox jumps over the lazy dog" 中每个字母的首次出现可以得到替换表。

示例 2:

输入:key = "eljuxhpwnyrdgtqkviszcfmabo", message = "zwx hnfx lqantp mnoeius ycgk vcnjrdb"
输出:"the five boxing wizards jump quickly"
解释:对照表如上图所示。
提取 "eljuxhpwnyrdgtqkviszcfmabo" 中每个字母的首次出现可以得到替换表。

 

提示:

  • 26 <= key.length <= 2000
  • key 由小写英文字母及 ' ' 组成
  • key 包含英文字母表中每个字符('a''z'至少一次
  • 1 <= message.length <= 2000
  • message 由小写英文字母和 ' ' 组成
lightbulb

解题思路

方法一:数组或哈希表

我们可以使用数组或哈希表 dd 存储对照表,然后遍历 message 中的每个字符,将其替换为对应的字符即可。

时间复杂度 O(m+n)O(m + n),空间复杂度 O(C)O(C)。其中 mmnn 分别为 keymessage 的长度;而 CC 为字符集大小。

1
2
3
4
5
6
7
8
9
10
class Solution:
    def decodeMessage(self, key: str, message: str) -> str:
        d = {" ": " "}
        i = 0
        for c in key:
            if c not in d:
                d[c] = ascii_lowercase[i]
                i += 1
        return "".join(d[c] for c in message)
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    The problem tests familiarity with hash table usage in string processing.

  • question_mark

    Look for clarity in the candidate’s approach to character mapping.

  • question_mark

    Watch for edge case handling like spaces in the message.

warning

常见陷阱

外企场景
  • error

    Failing to build the substitution table correctly by not considering the first occurrence of each letter in the key.

  • error

    Incorrectly handling spaces in the message.

  • error

    Overcomplicating the mapping process and missing a straightforward approach.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Using a shorter key that doesn’t cover all alphabet letters.

  • arrow_right_alt

    Adding punctuation in the message or key, requiring adjustments.

  • arrow_right_alt

    Changing the alphabet to lowercase and uppercase combinations.

help

常见问题

外企场景

解密消息题解:哈希·表·结合·string | LeetCode #2325 简单