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();
}
};
网友评论