[LeetCode] Decode the Message

2325. Decode the Message

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:

  1. Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table.
  2. Align the substitution table with the regular English alphabet.
  3. Each letter in message is then substituted using the table.
  4. Spaces ‘ ‘ are transformed to themselves.

For example, given key = “happy boy” (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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
string decodeMessage(string key, string message) {
unordered_map<char,int> mp;
int idx = 0;
for(int i = 0; i < key.length(); i++) {
if(key[i] == ' ') continue;
if(mp.count(key[i])) continue;
mp[key[i]] = idx++;
}
for(auto& ch : message) {
if(ch == ' ') continue;
ch = mp[ch] + 'a';
}
return message;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/03/PS/LeetCode/decode-the-message/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.