CodeWars - MorseCode  

by ne on 2022-02-16 under Algo/DS/Problems tagged with codility

Hi,
The problem description is in the comments above the solution below.

The problem belongs to CodeWars, you can try out it yourself on their platform.


/**
 *
 * The Morse code encodes every character as a sequence of "dots" and "dashes". For example, the letter A is coded as ?−, letter Q is coded as −−?−, and digit 1 is coded as ?−−−−. The Morse code is case-insensitive, traditionally capital letters are used. When the message is written in Morse code, a single space is used to separate the character codes and 3 spaces are used to separate words. For example, the message HEY JUDE in Morse code is ???? ? −?−−   ?−−− ??− −?? ?.
 *
 * NOTE: Extra spaces before or after the code have no meaning and should be ignored.
 *
 * In addition to letters, digits and some punctuation, there are some special service codes, the most notorious of those is the international distress signal SOS (that was first issued by Titanic), that is coded as ???−−−???. These special codes are treated as single special characters, and usually are transmitted as separate words.
 *
 * Your task is to implement a function that would take the morse code as input and return a decoded human-readable string.
 *
 * For example:
 *
 * MorseCodeDecoder.decode(".... . -.--   .--- ..- -.. .")
 * //should return "HEY JUDE"
 *
 */
import java.util.*;
import java.util.stream.*;
public class MorseCode {

    //given MorseCode dictionary
    static Map dict = new HashMap<>();

    public static String decode(String morseCode) {
        return Arrays.stream(morseCode.trim().split("   "))
                .map(w -> Arrays.stream(w.split(" "))
                        .map(c -> dict.get(c) != null ? dict.get(c) : "")
                        .collect(Collectors.joining("")))
                .collect(Collectors.joining(" "));
    }
}