Unique Morse Code Words

时间:2021-03-13 23:22:32

Algorithm

【leetcode】Unique Morse Code Words

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

1)problem

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.

2)answer

将26个因为字母映射为摩斯电码,然后根据每组字母每个字符对应的摩斯电码组合起来。至于那个简写是为什么可以那么写,没搞清楚。【"cba" can be written as "-.-..--...", (which is the concatenation "-.-." + "-..." + ".-").】

3)solution

#include "pch.h"
#include <stdio.h>
#include <string>
#include <vector>
#include <unordered_set>
using std::string;
using std::vector;
using std::unordered_set;

class Solution {
public:
    int uniqueMorseRepresentations(vector<string>& words) {
        vector<string> morse_code = { ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.." };
        // vector<string> store;
        unordered_set<string> result_val;
        int count = 0;
        for (auto str: words)
        {
            string tmp;
            for (auto ch: str)
            {
                //-'a'是找到输入字的索引。例如,'a' - 'a'为0.所以'a'对应于morse_code中的第一个元素。
                tmp += morse_code[(int)ch - (int)('a')];
            }

            result_val.insert(tmp);

        }
        return result_val.size();
    }
};

int main()
{
    vector<string> words;
    words.push_back("cba");
    // 使用内容
    Solution nSolution;
    nSolution.uniqueMorseRepresentations(words);
}