코린이의 소소한 공부노트

[LeetCode/Easy] 804. Unique Morse Code Words 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 804. Unique Morse Code Words

무지맘 2022. 12. 7. 18:24

1. Input

1) 문자열 배열 words

 

2. Output

1) words의 모든 문자열을 모스 부호로 바꿨을 때 나올 수 있는 모스 부호의 수

 

3. Constraint

1) 1 <= words.length <= 100

2) 1 <= words[i].length <= 12

3) words[i]는 영어 소문자로만 이루어져 있다.

 

4. Example

Input: words = {"gin","zen","gig","msg"} -> Output: 2

설명: 각 단어를 모스부호로 바꿔보면

- "gin" -> "--...-."

- "zen" -> "--...-." -> “gin”과 같음

- "gig" -> "--...--."

- "msg" -> "--...--." -> “gig”와 같음

"--...-.“"--...--.". 2가지 모스 부호가 있으므로 2를 반환한다.

 

5. Code

1) 첫 코드(2022/06/14)

if(words.length == 1) return 1;

String[] tf = new String[words.length];
String[] code = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; // 문제에서 제공해준 것

String s = "";
for(int i=0 ; i<tf.length ; i++){
    for(int j=0 ; j<words[i].length() ; j++)
        s += code[words[i].charAt(j)-97];
    tf[i] = s;
    s = "";
}

List<String> unique = new ArrayList();
unique.add(tf[0]);
for(int i=1 ; i<tf.length ; i++){
    if(!unique.contains(tf[i]))
        unique.add(tf[i]);
} // for i

return unique.size();