804. Unique Morse Code Words
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:
1 | [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] |
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.
1 | Example: |
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.
大概解释一下题目:摩斯码,26个小写字母各对应一串密码串,不同的英文单词可能出现同样的摩斯码;
输入:一个数组,数组中包含多个单词;
输出:单词转换成摩斯码后,总的摩斯编码类别有几种;
解题思路:
- 要得到不同的摩斯码,就是不能有重复的,就可以用集合(set)来存储转换后的摩斯码;
- 26个小写字母对应的摩斯码是固定的,就用数组直接初始化;
- 字母a对应的ASCII码为97,数组第一个元素的索引index为0,直接减去97即可得到对应的摩斯码编码;
- 循环遍历vector中的word,循环遍历word中的每一个字母;
代码如下:
1 | class Solution { |
result
Runtime: 4 ms, faster than 100.00% of C++ online submissions for Unique Morse Code Words.
Memory Usage: 8.7 MB, less than 100.00% of C++ online submissions for Unique Morse Code Words.