804. 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, "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 "--...--.".

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


題中介紹了摩斯密碼,在摩斯密碼中每個(gè)英文的單詞對(duì)應(yīng)唯一的密碼格式,比如‘a(chǎn)’對(duì)應(yīng)的就是'.-'(莫斯密碼不區(qū)分大小寫)。題中會(huì)給出一個(gè)單詞列表,讓我們將其這些單詞轉(zhuǎn)換為摩斯密碼,其中每個(gè)單詞的莫斯密碼就是單詞中字符對(duì)應(yīng)的摩斯密碼拼接起來(lái),找出這些這單轉(zhuǎn)換成摩斯密碼之后一共有幾種不同的形式。


將單詞進(jìn)行遍歷,然后找出它們對(duì)應(yīng)的摩斯密碼添加到一個(gè)set中,由于set能夠確保唯一性,所以最后返回set的長(zhǎng)度即可。

cpp:

class Solution {
public:
    int uniqueMorseRepresentations(vector<string>& words) {
        set<string> uniqueMorse;// 保存摩斯密碼,set確保唯一性

        // 定義摩斯密碼
        vector<string> morse = {".-","-...","-.-.","-..",".","..-.","--.",
                         "....","..",".---","-.-",".-..","--","-.",
                         "---",".--.","--.-",".-.","...","-","..-",
                         "...-",".--","-..-","-.--","--.."};

        // 遍歷所有的單詞
        for(string word : words) {
            string morseForWord = "";// 保存單詞的摩斯密碼
            for(char ch : word) { //將單詞轉(zhuǎn)換為對(duì)應(yīng)的摩斯密碼
                morseForWord += morse[ch - 'a']; // 將摩斯密碼記錄下來(lái)
            }
            uniqueMorse.insert(morseForWord);
        }
        return uniqueMorse.size();
    }
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容