컴퓨터공학/LeetCode 1000

[LeetCode] 804. Unique Morse Code Words

saurus2 2022. 8. 17. 13:50

804. Unique Morse Code Words

Easy

International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:

  • 'a' maps to ".-",
  • 'b' maps to "-...",
  • 'c' maps to "-.-.", and so on.

For convenience, the full table for the 26 letters of the English alphabet is given below:

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter.

  • For example, "cab" can be written as "-.-..--...", which is the concatenation of "-.-.", ".-", and "-...". We will call such a concatenation the transformation of a word.

Return the number of different transformations among all words we have.

 

Example 1:

Input: words = ["gin","zen","gig","msg"]
Output: 2
Explanation: The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
There are 2 different transformations: "--...-." and "--...--.".

Example 2:

Input: words = ["a"]
Output: 1

 

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 12
  • words[i] consists of lowercase English letters.

문제 풀이

문제 접근

글자길이는 100, 글자수는 최대 12이기 때문에 N^2 시간복잡도로도 풀 수 있어보인다.

풀이

문제에서 주어지는 모스부호 리스트를 그대로 사용한다.

중복되는 문자를 거르기 위해서 set을 사용한다.

각 문자별로 모스부호를 할당하지 않고, 'a' 아스키 코드 값을 빼서 0부터 값이 매긴다. 

모스부호로 바꾼후 set 에 저장하여 중복을 거르고, set 의 길이를 반환한다.

소스 코드

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        a = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        hashset = set()
        for word in words:
            temp = ''
            for letter in word:
                temp += a[ord(letter) - ord('a')]
            hashset.add(temp)
        return len(hashset)