![]() |
VOOZH | about |
Design a Morse Code Translator that converts Morse code into English text. The Morse code consists of dots (.) and dashes (-) representing letters and numbers. Spaces(' ') separate letters, and forward slash('/') separate words. Implement a program to perform this translation.
Input: Morse Code: "... --- ..."
Output: English Text: "SOS"
Explanation: The Morse code "..." represents 'S', "---' represents 'O', and the spaces separate the letters. Therefore, the translation is "SOS."Input: Morse Code: "-- --- .-. ... . / -.-. --- -.. . / .. ... / ..-. --- .-. --. . - - .- -... .-.. ."
Output: English Text: "MORSE CODE IS FORGETTABLE"
Explanation: Each Morse code sequence represents the corresponding letter or word. The spaces between Morse code sequences indicate separation between letters and '/' represents spaces between words.
Approach: To solve the problem, follow the below idea:
The problem can be solved by using a map or dictionary to store the letters and digits corresponding to morse code. Split the morse code into words (separated by three spaces) and then into individual letters (separated by single space). After separating the letters look up for each letter in the dictionary to find the corresponding English letter.
Step-by-step algorithm:
Illustration of algorithm:
Let's take the Morse code input "... --- ..." as an example:
["...", "---", "..."][['.'], ['---'], ['...']][['S'], ['O'], ['S']]'SOS'Below is the implementation of the above approach:
Morse Code: -- --- .-. ... . / -.-. --- -.. . / .. ... / ..-. --- .-. --. . - - .- -... .-.. . English Text: MORSE CODE IS FORGETTABLE
Time Complexity: O(N), where N is the length of the Morse code input string. This is because we iterate through the Morse code input string once, and each operation inside the loop is constant time.
Auxiliary Space: O(1), as we use constant space for the dictionary.