|
| 1 | +/** |
| 2 | + * 2325. Decode the Message |
| 3 | + * https://leetcode.com/problems/decode-the-message/ |
| 4 | + * Difficulty: Easy |
| 5 | + * |
| 6 | + * You are given the strings key and message, which represent a cipher key and a secret message, |
| 7 | + * respectively. The steps to decode message are as follows: |
| 8 | + * 1. Use the first appearance of all 26 lowercase English letters in key as the order of the |
| 9 | + * substitution table. |
| 10 | + * 2. Align the substitution table with the regular English alphabet. |
| 11 | + * 3. Each letter in message is then substituted using the table. |
| 12 | + * 4. Spaces ' ' are transformed to themselves. |
| 13 | + * 5. For example, given key = "happy boy" (actual key would have at least one instance of each |
| 14 | + * letter in the alphabet), we have the partial substitution table of ('h' -> 'a', 'a' -> 'b', |
| 15 | + * 'p' -> 'c', 'y' -> 'd', 'b' -> 'e', 'o' -> 'f'). |
| 16 | + * |
| 17 | + * Return the decoded message. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {string} key |
| 22 | + * @param {string} message |
| 23 | + * @return {string} |
| 24 | + */ |
| 25 | +var decodeMessage = function(key, message) { |
| 26 | + const substitution = new Map(); |
| 27 | + let alphabetIndex = 0; |
| 28 | + |
| 29 | + for (const char of key) { |
| 30 | + if (char !== ' ' && !substitution.has(char)) { |
| 31 | + substitution.set(char, String.fromCharCode(97 + alphabetIndex++)); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + let result = ''; |
| 36 | + for (const char of message) { |
| 37 | + result += char === ' ' ? ' ' : substitution.get(char); |
| 38 | + } |
| 39 | + |
| 40 | + return result; |
| 41 | +}; |
0 commit comments