804. 唯一摩尔斯密码词
国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: "a" 对应 ".-", "b" 对应 "-...", "c" 对应 "-.-.", 等等。
为了方便,所有26个英文字母对应摩尔斯密码表如下:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,"cab" 可以写成 "-.-.-....-",(即 "-.-." + "-..." + ".-"字符串的结合)。我们将这样一个连接过程称作单词翻译。
题解
var uniqueMorseRepresentations = function(words) {
var b = []
for (var i = 0; i < words.length; i++) {
var w = words[i].split('')
for (var j = 0; j < w.length; j++) {
switch (w[j]) {
case 'a':
w[j] = ".-";
break;
case 'b':
w[j] = "-...";
break;
case 'c':
w[j] = "-.-.";
break;
case 'd':
w[j] = "-..";
break;
case 'e':
w[j] = ".";
break;
case 'f':
w[j] = "..-.";
break;
case 'g':
w[j] = "--.";
break;
case 'h':
w[j] = "....";
break;
case 'i':
w[j] = "..";
break;
case 'j':
w[j] = ".---";
break;
case 'k':
w[j] = "-.-";
break;
case 'l':
w[j] = ".-..";
break;
case 'm':
w[j] = "--";
break;
case 'n':
w[j] = "-.";
break;
case 'o':
w[j] = "---";
break;
case 'p':
w[j] = ".--.";
break;
case 'q':
w[j] = "--.-";
break;
case 'r':
w[j] = ".-.";
break;
case 's':
w[j] = "...";
break;
case 't':
w[j] = "-";
break;
case 'u':
w[j] = "..-";
break;
case 'v':
w[j] = "...-";
break;
case 'w':
w[j] = ".--";
break;
case 'x':
w[j] = "-..-";
break;
case 'y':
w[j] = "-.--";
break;
case 'z':
w[j] = "--..";
break;
}
}
b.push(w.join(''))
}
for (var k = 0; k < b.length; k++) {
if (b.indexOf(b[k]) != k) {
b.splice(k, 1);
k--;
}
}
return b.length
};