804. Unique Morse Code Words

Question 804

https://leetcode.com/problems/unique-morse-code-words/

nternational 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.

Now, given a list of words, 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 "-.-." + "-..." + ".-"). We'll call such a concatenation, the transformation of a word.

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

Example:
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 "--...--.".

Answer

v1. use Dictionary + SET (100%)

  1. 將 Morse Code 和 字母做成對應的 Dictionary

  2. 創立一個 SET 來儲存結果

  3. 以每個字為單位,轉成 Morse Code 後存進 SET 中

  4. return set 的長度(所含相異值個數)

v2. use ord() + SET (98.39%)

  1. 將題目中的 Morse Code 設定為一 List

  2. 創立一個 SET 來儲存結

  3. 將每個字母轉換成 ASCII 再減 97 即是 List 中相對應的位置

  4. 以每個字為單位,轉成 Morse Code 後存進 SET 中

  5. return set 的長度(所含相異值個數)

set 的好處是 在 add 的時候,若有重複則不會再加入。可以確定裡面的集合都是單一的值。

class Solution(object):
    def uniqueMorseRepresentations(self, words):
        
        # define Morse Code
        MorseCodeDic = {'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':"--.."}
        # create set 
        AnserSet = set()
        
        for word in words:
            word2morse = ""
            for alphabet in word:
                word2morse += MorseCodeDic[alphabet]
            AnserSet.add(word2morse)
                
        return len(AnserSet)

welcome to check my Github LeetCode-share(https://github.com/QuenLo/LeeCode-share)

Last updated