804. Unique Morse Code Words

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

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 “–…–.”.
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.

題目翻譯:

國際莫爾斯電碼定義了一種標準編碼,其中每個字母映射到一系列點和短劃線,如下所示:“a”映射到“.-”,“b”映射到“-…”,“c”映射到“-。-。“, 等等。

為方便起見,下面給出了 26 個英文字母的完整表格:

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

現在,給定一個單詞列表,每個單詞可以寫成串聯每個字母的摩爾斯電碼。例如,“cba”可以寫成”-.-..–…”,(這是串聯”-.-.” + “-…” + “.-“)。我們稱之為串聯,即一個詞的轉換。

返回我們所有單詞中不同變換的數量。

程式思路:

利用 set 容器的特性,輕鬆就能做出此題

class Solution {
public:
    int uniqueMorseRepresentations(vector<string>& words) {
        set <string> transformations;
        vector <string >Morse_table = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        for(auto word : words)
        {
            string tmp;
            for (int i = 0; i < word.length();i++)
            {
               auto offset = (word[i] - 'a');
               if(offset < Morse_table.size())
                    tmp += Morse_table[offset];
               else
                    break; //invalid char;
            }
            transformations.insert(tmp);
        }
        return transformations.size();
    }
}

  目錄