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/


题中介绍了摩斯密码,在摩斯密码中每个英文的单词对应唯一的密码格式,比如‘a’对应的就是’.-‘(莫斯密码不区分大小写)。题中会给出一个单词列表,让我们将其这些单词转换为摩斯密码,其中每个单词的莫斯密码就是单词中字符对应的摩斯密码拼接起来,找出这些这单转换成摩斯密码之后一共有几种不同的形式。


将单词进行遍历,然后找出它们对应的摩斯密码添加到一个set中,由于set能够确保唯一性,所以最后返回set的长度即可。

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) { //将单词转换为对应的摩斯密码
                morseForWord += morse[ch - 'a']; // 将摩斯密码记录下来
            }
            uniqueMorse.insert(morseForWord);
        }
        return uniqueMorse.size();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值