Skip to content

2325. Decode the Message 👍

  • Time: $O(|\texttt{key}| + |\texttt{message}|)$
  • Space: $O(128 + |\texttt{message}|) = O(|\texttt{message}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  string decodeMessage(string key, string message) {
    vector<char> keyToActual(128);
    keyToActual[' '] = ' ';
    char currChar = 'a';

    for (const char c : key)
      keyToActual[c] = keyToActual[c] ?: currChar++;

    transform(message.cbegin(), message.cend(), message.begin(),
              [&](char c) { return keyToActual[c]; });

    return 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) {
    StringBuilder sb = new StringBuilder();
    char[] keyToActual = new char[128];
    keyToActual[' '] = ' ';
    char currChar = 'a';

    for (final char c : key.toCharArray())
      if (keyToActual[c] == 0)
        keyToActual[c] = currChar++;

    for (final char c : message.toCharArray())
      sb.append(keyToActual[c]);

    return sb.toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def decodeMessage(self, key: str, message: str) -> str:
    keyToActual = {' ': ' '}
    currChar = 'a'

    for c in key:
      if c not in keyToActual:
        keyToActual[c] = currChar
        currChar = chr(ord(currChar) + 1)

    return ''.join(keyToActual[c] for c in message)