LeetCode Problem -- 804. Unique Morse Code Words

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38088298/article/details/81586416
  • 描述: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 “–…–.”.

  • 分析:这道题给出了26个字母的对应转换方式,要求根据这个转换方式对一组字符串进行转换,求出共有多少组不同的转换方式。
  • 思路一:遍历字符串+STL-map+STL-set
class Solution {
public:
    int uniqueMorseRepresentations(vector<string>& words) {
    string change[26] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        map<char, string> my_map;
        set<string> result_str;
        for (int i = 0; i < 26; i++) {
            my_map['a' + i] = change[i];
        }
        for (int i = 0; i < words.size(); i++) {
            string temp = "";
            for (int j = 0; j < words[i].length(); j++) {
                temp = temp + my_map.find(words[i][j]) -> second;
            }
            result_str.insert(temp);
        }
        return result_str.size();
}
};

猜你喜欢

转载自blog.csdn.net/m0_38088298/article/details/81586416