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**_ p _**y**_ _**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').

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**_ ".

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**_ ".
We can decode the message by building a mapping from the first appearance of each letter in the key to the regular English alphabet. Then, we substitute each character in the message using this mapping. This works because the key contains every letter at least once, so the mapping is always complete.
classSolution {
public String decodeMessage(String key, String message) {
Map<Character, Character> mp =new HashMap<>();
char ch ='a';
for (char c : key.toCharArray()) {
if (c !=' '&&!mp.containsKey(c)) {
mp.put(c, ch++);
}
}
StringBuilder ans =new StringBuilder();
for (char c : message.toCharArray()) {
ans.append(c ==' '?' ' : mp.get(c));
}
return ans.toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
fundecodeMessage(key: String, message: String): String {
val mp = mutableMapOf<Char, Char>()
var ch = 'a'for (c in key) {
if (c !=' '&& mp[c] ==null) {
mp[c] = ch++ }
}
val ans = StringBuilder()
for (c in message) {
ans.append(if (c ==' ') ' 'else mp[c])
}
return ans.toString()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defdecodeMessage(self, key: str, message: str) -> str:
mp: dict[str, str] = {}
ch = ord('a')
for c in key:
if c !=' 'and c notin mp:
mp[c] = chr(ch)
ch +=1 ans = []
for c in message:
ans.append(' 'if c ==' 'else mp[c])
return''.join(ans)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfndecode_message(key: String, message: String) -> String {
use std::collections::HashMap;
letmut mp = HashMap::new();
letmut ch =b'a';
for c in key.bytes() {
if c !=b' '&&!mp.contains_key(&c) {
mp.insert(c, ch);
ch +=1;
}
}
message.bytes().map(|c| {
if c ==b' ' { ' ' } else { mp[&c] aschar }
}).collect()
}
}