Morse Code Encoder and Decoder Medium · Topics · Company Tags · Hints
You are given a standard mapping from each lowercase English letter to its Morse code representation (a string of dots '.' and dashes '-'). Your task is to implement two operations:
Encoding – Given a word consisting of lowercase letters, return its Morse code form. The form is obtained by replacing every letter with its corresponding code and concatenating all codes together without any separators.
Decoding – Given a string that contains only dots and dashes, return every possible word (a string of lowercase letters) that, when encoded with the same mapping, produces exactly the given input string. The words in the result list may be returned in any order.
The fixed mapping is as follows:
a ".-" b "-..." c "-.-." d "-.."
e "." f "..-." g "--." h "...."
i ".." j ".---" k "-.-" l ".-.."
m "--" n "-." o "---" p ".--."
q "--.-" r ".-." s "..." t "-"
u "..-" v "...-" w ".--" x "-..-"
y "-.--" z "--.."
Example 1 (encoding):
Input: word = "hello"
Output: ".....-..-..---"
Explanation: h → "....", e → ".", l → ".-..", l → ".-..", o → "---". Concatenating gives "....." + ".-.." + ".-.." + "---" = ".....-..-..---".
Example 2 (encoding):
Input: word = "a"
Output: ".-"
Example 3 (decoding):
Input: morse = "..."
Output: ["s", "eee"] (order does not matter)
Explanation: The string "..." can be the single letter 's' (code "...") or three 'e' letters ("e" is "."), which concatenate to "...". Both are valid.
Constraints (encoding):
1 <= word.length <= 100Constraints (decoding):
1 <= morse.length <= 30'.' and '-' characters.