问题描述
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 "--...--.".
思路:将将每个word转换成morse码,转换方法是先计算出每个word中的每个字母与字母a的距离,然后就可以从数组 alphabet中取到每个字母的morse码,然后将一个word中的每一个Morse码拼接起来;在遍历所有的words时候,将每个word对应的morse码定义为某个对象的属性,循环一次就判断一下该属性是否在这个对象中,不在的话,num++; 注意,不要忘记给对象的属性赋值,否则会出错
var morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."];
function to_morse(word){
var ret = [];
for(i in word){
var c = word[i].charCodeAt() - 'a'.charCodeAt();
s = morse[c];
ret.push(s);
}
return ret.join('');
}
var uniqueMorseRepresentations = function(words){
d = {};
var num =0;
for(j in words){
var s = to_morse(words[j]);
if(!(s in d)){
num++;
}
d[s] = 1;
}
return num;
}
文末彩蛋
Day 21.Unique Morse Code Words(804)
网友评论