CodeWars 열 일곱 번째 문제
Updated:
Decode the Morse code
public class DecodeTheMorseCode {
HashMap<String,String> morsdeCodeHashMap = new HashMap<String,String>();
public DecodeTheMorseCode() {
String mosString[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ""};
String alpabatString[] = {"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", " "};
for(int i=0; i < mosString.length ; i++) {
morsdeCodeHashMap.put(mosString[i], alpabatString[i]);
}
}
public String decode(String morseCode) {
String decodeMorseCode = "";
String[] splitMorseCodeArrays = morseCode.trim().split(" ");
for(int i = 0; i < splitMorseCodeArrays.length; i++) {
String splitMorseCode = splitMorseCodeArrays[i];
if(splitMorseCode.length() == 0) {
i++;
}
decodeMorseCode += morsdeCodeHashMap.get(splitMorseCode);
}
return decodeMorseCode;
}
}
*모스코드 table의 경우 사이트에서 제공하기 때문에 사이트에서 제공하는 함수(MorseCode.get(String)를 썼다.
*나는 스프링에서 돌렸기 때문에 임의로 모스코드 테이블을 생성하여 풀었다.
*Best 코드 대부분 이중 for을 이용하여 풀었다. 나는 성능을 고려하여 for 한개만 쓰고 싶어서 split을 space 1개로 구분하였다.
*단어별 구분은 space가 3개 들어오기 때문에 한 개 space로 split 할 경우 String 배열에 공백이 2개 들어간다. 그래서 split한 배열에서 뽑아 올때 ““들어가 있는 인자는 i를 ++하여 출력할 string에 space를 한 번만 넣는다.
*문제는 모스부호 양쪽에 공백이 들어올 경우 오류가 발생하였다. 이를 위해 trim을 통해서 해결하였다.