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();
}
};