1

1.题目
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:

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

Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cba" 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 "--...--.".
  1. 自己的解决方法
class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        final_set = set()
        mosLIst = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        for word in words:
            temp = ''
            for i in word:
                temp += mosLIst[ord(i)-97]
            final_set.add(temp)
        return len(final_set)
Runtime: 36 ms, faster than 97.45% of Python3 online submissions for Unique Morse Code Words.
Memory Usage: 12.9 MB, less than 5.36% of Python3 online submissions for Unique Morse Code Words.

3.其他解决方法

const codes = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

const getIdx = char => char.charCodeAt(0) - 'a'.charCodeAt(0)

var uniqueMorseRepresentations = function(words) {
    return words.map( word => word.split('')
                                 .map( char => codes[getIdx(char)])
                                 .join(''))
                .reduce((set, cur) => set.add(cur), new Set())
                .size
};

lllluull
135 声望9 粉丝