# 804 Unique Morse Code Words

可以先把題目存進 obj 或 array ,之後直接用 Big O (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.

input: 給一字串陣列
output: 轉成 Morse Code 後回傳有幾個不同的結合
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 "--...--.".
Note:

The length of words will be at most 100.
Each words[i] will have length in range [1, 12].
words[i] will only consist of lowercase letters.
*/

/**
 * @param {string[]} words
 * @return {number}
 */
var uniqueMorseRepresentations = function(words) {
  
};

怎麼解

前面會用 Array method,然後也利用 Set 回傳不重覆值的 size

  • 先把英文數字轉成 a = 0, b = 1,... z = 26,這樣到時候才能抓摩斯密碼

  • 看每一個 words (ex. "gin")

  • 再看每一個 word (ex. g, i, n)

  • 轉成摩斯密碼後合併起來

const alphabet = {
    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: '--..' 
}

const uniqueMorseRepresentations = words => {  
    return new Set(words.map(word => {
        return word.split('').map(letter => alphabet[letter]).join(''))).size
    }
}

學到什麼?

  • 本來一開始想法是用 charCodeAt 先計算每個字母代表數字然後再去對應 Morse Code

let getIndex = char => char.charCodeAt(0) - "a".charCodeAt(0)

結果其實可以一開始就存在 obj 裡,就不用再計算一次了.效能也增加 30% 呢

Last updated