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, "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.
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.
题目大意:
每个字母对应一个摩斯码,一个字符串可以相应的转化为摩斯码组成的序列。不同字符串也可能产生相同的摩斯码序列。题目给出几个字符串,要求求出对应的摩斯码序列的种类。
方法一:
要求求产生的字符串的种类,以及每个字母对应一个摩斯码,一下想到了map。
将字符串产生的摩斯码序列放入结果map中,最后求出结果map的大小就是摩斯码的种类数。
代码如下:
class Solution { public: int uniqueMorseRepresentations(vector<string>& words) { map<char,string> wordsMap={{'a',".-"},{'b',"-..."},{'c',"-.-."},{'d',"-.."},{'e',"."},{'f',"..-."},{'g',"--."},{'h',"...."},{'i',".."},{'j',".---"},{'k',"-.-"},{'l',".-.."},{'m',"--"},{'n',"-."},{'o',"---"},{'p',".--."},{'q',"--.-"},{'r',".-."},{'s',"..."},{'t',"-"},{'u',"..-"},{'v',"...-"},{'w',".--"},{'x',"-..-"},{'y',"-.--"},{'z',"--.."}}; if (words.empty())return 0; map<string, int> res; for (int i = 0; i < words.size(); ++i) { string temp = ""; for (int j = 0; j < words[i].size(); ++j) { temp.insert(temp.size(), wordsMap[words[i][j]]); } res.insert({ temp, 1 }); } return res.size(); } };
*注意:
1.往string中插入字符使用insert()函数,第一个参数表示放置该字符的位置,类型是int,第二个参数是插入的字符。
2.往map中插入元素使用insert()函数,元素类型是map的元素类型键值对,因此要加{}将键值对包括起来。
方法二:
由于结果并不需要键值对,因为卫星数据并无意义,所以使用集合set代替map。另外,因为摩斯码表是按照字母顺序排列的,相比从map中对应找出字母的摩斯码,也可以根据字母顺序直接从数组中取出。
方法二的解题思路和方法一相同,在参考其他答案的基础上对数据结构进行了调整。
代码如下:
class Solution { public: int uniqueMorseRepresentations(vector<string>& words) { vector<string> wordsSet={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; unordered_set<string> res; for(string word:words){ string temp=""; for(char c:word){ temp+=wordsSet[c-'a']; } res.insert(temp); } return res.size(); } };