804. Unique Morse Code Words

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 "--...--.".

这个题目是说把一个数组的单词转换成morse密码,输出不重复的morse密码个数。

思路是先遍历单词数组,根据给定的morse密码数组把单词转换成morse字符串;使用一个数组来存放每次转换后的字符串,在每次加入数组前先比较是否已经有相同的字符串,如果没有则计数器加1。

C++实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
vector<string> morse;
int result = 0;
morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};

vector<string> morsewords;
//遍历words,转换为morse,比较计数
for(string word:words){
string ctomorse = "";
bool flag = true;
for(char c:word){
ctomorse += morse[c-'a']; //word转化为morse
}
//先判断是否存在
for(string wordmorse:morsewords){
if(ctomorse==wordmorse){
flag = false;
break;
}else{
continue;
}
}
if(flag){
result += 1;
}
//后加入数组
morsewords.push_back(ctomorse); //注意一下这里使用push_back()
}
return result;
}
};

需要注意的地方是vector的使用。一开始使用morsewords[i]这样的数组的方法加入vector,这样不能动态地改变vector的长度,一旦初始化确定长度之后又会因为长度固定了结果不对。所以需要使用push_back()函数动态地加入,就不需要初始化指定长度。

Javascript实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* @param {string[]} words
* @return {number}
*/
var uniqueMorseRepresentations = function(words) {
var morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."];
var count = 0;
var morsewords = [];
//遍历words
for(let word of words){
var morseword = '';
var a = 'a';

var flag = true;
for(let c of word){
morseword += morse[c.charCodeAt(0)-a.charCodeAt(0)]; //每个word转换为morseword
}

for(let m of morsewords){
if(morseword == m){
flag = false;
break;
}else {
continue
}
}
if(flag){
count +=1;
}
morsewords.push(morseword);
}
return count;
};

用js实现的时候在ASCII码转换的时候不能直接像C++那样字符的加减,需要使用charCodeAt()函数,将字符串的第几个字符转换成ACII码。

贴一下解答里面的js的实现方法,学习一下。

1
2
3
4
5
var uniqueMorseRepresentations = function(words) {
const mapping = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."];
const charToIndex = char => char.charCodeAt(0) - 97;
return new Set(words.map(word => word.split('').reduce((morseCode, cur) => morseCode + mapping[charToIndex(cur)], ''))).size;
};