2325. Decode the Message

2325. Decode the Message

Description

You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows:

  • Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table.

  • Align the substitution table with the regular English alphabet.

  • Each letter in message is then substituted using the table.

  • Spaces ' ' are transformed to themselves.

  • For example, given key = "hap py bo y" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ('h' -> 'a', 'a' -> 'b', 'p' -> 'c', 'y' -> 'd', 'b' -> 'e', 'o' -> 'f').

Return the decoded message.

Example 1:

1
2
3
4
Input: key = "the quick brown fox jumps over the lazy dog", message = "vkbs bs t suepuv"
Output: "this is a secret"
Explanation: The diagram above shows the substitution table.
It is obtained by taking the first appearance of each letter in "**the** **quick** **brown** **f** o**x** **j** u**mps** o**v** er the **lazy** **d** o**g** ".

Example 2:

1
2
3
4
Input: key = "eljuxhpwnyrdgtqkviszcfmabo", message = "zwx hnfx lqantp mnoeius ycgk vcnjrdb"
Output: "the five boxing wizards jump quickly"
Explanation: The diagram above shows the substitution table.
It is obtained by taking the first appearance of each letter in "**eljuxhpwnyrdgtqkviszcfmabo** ".

Constraints:

  • 26 <= key.length <= 2000
  • key consists of lowercase English letters and ' '.
  • key contains every letter in the English alphabet ('a' to 'z') at least once .
  • 1 <= message.length <= 2000
  • message consists of lowercase English letters and ' '.

Hints/Notes

  • 2025/05/05 Q1
  • String
  • No solution from 0x3F or Leetcode

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
string decodeMessage(string key, string message) {
unordered_map<char, char> mapping;
char cur_key = 'a';
for (char& c : key) {
if (isalpha(c) && !mapping.contains(c)) {
mapping[c] = cur_key;
cur_key++;
}
if (mapping.size() >= 26) {
break;
}
}
string res;
for (char c : message) {
if (isalpha(c)) {
res.push_back(mapping[c]);
} else {
res.push_back(' ');
}
}
return res;
}
};