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 "--...--.".
Note:
- The length of
words
will be at most100
. - Each
words[i]
will have length in range[1, 12]
. words[i]
will only consist of lowercase letters.
這道題說的就是大名鼎鼎的摩斯碼了,給了我們所有字母的摩斯碼的寫法,然后給了我們一個單詞數組,問我們表示這些單詞的摩斯碼有多少種。因為某些單詞的摩斯碼表示是相同的,比如gin和zen就是相同的。最簡單直接的方法就是我們求出每一個單詞的摩斯碼,然后將其放入一個HashSet中,利用其去重復的特性,從而實現題目的要求,最終HashSet中元素的個數即為所求,參見代碼如下:
class Solution { public: int uniqueMorseRepresentations(vector<string>& words) { vector<string> morse{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; unordered_set<string> s; for (string word : words) { string t = ""; for (char c : word) t += morse[c - 'a']; s.insert(t); } return s.size(); } };
討論:這道題其實沒有充分發揮其潛力,摩斯碼的場景很好,只是作為一道Easy題未免有些可惜了。一個比較顯而易見的follow up就是,給我們一個摩斯碼,問其有幾種可能的單詞組,比如給我們一個"--...-.",那么我們知道至少有兩種zen和gin,可能還有更多,這樣是不是就更加有趣了呢?
類似題目:
https://leetcode.com/problems/unique-morse-code-words/solution/