Decode the Message

easy string hash map

Problem

You are given a string key and a string message. The first appearance of every one of the 26 lowercase letters in key (ignoring spaces) forms a substitution table: that letter maps to 'a', the next new letter to 'b', and so on. Decode message by replacing each letter with its mapped value; spaces stay as spaces.

Inputkey = "the quick brown fox jumps over the lazy dog", message = "vkbs"
Output"this"
The first distinct letters of key map t→a, h→b, e→c, q→d, u→e, ... , giving v→t, k→h, b→i, s→s; so "vkbs" decodes to "this".

def decode_message(key, message):
    table = {}
    nxt = ord('a')
    for ch in key:
        if ch != ' ' and ch not in table:
            table[ch] = chr(nxt)
            nxt += 1
    return "".join(table.get(c, ' ') for c in message)
function decodeMessage(key, message) {
  const table = {};
  let nxt = 0;
  for (const ch of key) {
    if (ch !== ' ' && !(ch in table)) {
      table[ch] = String.fromCharCode(97 + nxt);
      nxt++;
    }
  }
  let out = "";
  for (const c of message) out += c === ' ' ? ' ' : table[c];
  return out;
}
class Solution {
    public String decodeMessage(String key, String message) {
        char[] table = new char[128];
        char nxt = 'a';
        for (char ch : key.toCharArray()) {
            if (ch != ' ' && table[ch] == 0) {
                table[ch] = nxt++;
            }
        }
        StringBuilder out = new StringBuilder();
        for (char c : message.toCharArray())
            out.append(c == ' ' ? ' ' : table[c]);
        return out.toString();
    }
}
string decodeMessage(string key, string message) {
    char table[128] = {0};
    char nxt = 'a';
    for (char ch : key) {
        if (ch != ' ' && table[(int)ch] == 0) {
            table[(int)ch] = nxt++;
        }
    }
    string out = "";
    for (char c : message)
        out += (c == ' ') ? ' ' : table[(int)c];
    return out;
}
Time: O(|key| + |message|) Space: O(1)