题目
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. The Morse code table is preloaded for you as a dictionary, feel free to use it: Java:
MorseCode.get(".--")
莫尔斯电码将每个字符编码为一系列的“点”和“破折号”。例如,字母A编码为·-,字母Q编码为·-·-,数字1编码为·-·-。摩尔斯电码不区分大小写,传统上使用大写字母。当信息是用莫尔斯电码写的时候,一个空格用来分隔字符码,三个空格用来分隔单词。例如,莫尔斯电码中的消息HEY JUDE是 ···· · −·−− ·−−− ··− −·· · 注意:在除了字母、数字和一些标点符号,还有一些特殊的服务代码,其中最臭名昭著的是国际求救信号SOS(最初由泰坦尼克号发出),其编码为····-··-··。这些特殊代码被视为单个特殊字符,通常作为单独的字符传输。 你的任务是实现一个函数,将摩尔斯电码作为输入,并返回一个解码后的人类可读文件字符串。 字符串莫尔斯电码表作为字典预先加载,您可以随意使用: Java:MorseCode.get(".--")
例子
MorseCodeDecoder.decode(“…. . -.— .—- ..- -.. .”) //should return “HEY JUDE”
分析
翻译摩斯电码,已经提供了摩斯电码表字典,我们要做的只是把字符串切分、匹配、组合而已,比较简单
我的解法
import java.util.*;
import java.util.stream.Collectors;
public class MorseCodeDecoder {
public static String decode(String morseCode) {
return Arrays.stream(morseCode.split(" ")).map(
word -> Arrays.stream(word.split(" ")).filter(e -> MorseCode.get(e)!= null).map(e -> MorseCode.get(e) ).collect(Collectors.joining())
).collect(Collectors.joining(" ")).trim();
}
}
参考解法
public class MorseCodeDecoder {
public static String decode(String morseCode) {
String result = "";
for(String word : morseCode.trim().split(" ")) {
for(String letter : word.split("\\s+")) {
result += MorseCode.get(letter);
}
result += ' ';
}
return result.trim();
}
}
import java.util.Arrays;
import java.util.stream.Collectors;
public class MorseCodeDecoder {
public static String decode(String morseCode) {
return Arrays.stream(morseCode.trim().split(" "))
.map(MorseCodeDecoder::decodeWord)
.collect(Collectors.joining(" "));
}
private static String decodeWord(String word) {
return Arrays.stream(word.split(" ")).map(MorseCode::get).collect(Collectors.joining());
}
}
提升
- 我们可以通过
::
关键字来访问类的构造方法,对象方法,静态方法。