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:
[“.-”,“-…”,“-.-.”,“-…”,“.”,“…-.”,“–.”,“…”,“…”,“.—”,“-.-”,“.-…”,“–”,“-.”,“—”,“.–.”,“–.-”,“.-.”,“…”,“-”,“…-”,“…-”,“.–”,“-…-”,“-.–”,“–…”]
Given an array of strings words where 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 of “-.-.”, “.-”, and “-…”. We will call such a concatenation the transformation of a word.
Return the number of different transformations among all words we have.
Example 1:
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 “–…–.”.
每个字母对应一个摩斯码,单词的摩斯码是字母摩斯码的拼接。
字符串数组words的单词中,有多少个不同的摩斯码。
思路:
就是简单地把每个单词的摩斯码都拼出来,然后看有几个不同的。
可用HashSet保存单词的摩斯码,重复的也只会保存一个,最后看hashSet的size即可。
拼摩斯码时可以直接用string的拼接,即string1 + string2的形式,
但是注意了,这个耗内存会比StringBuilder要大(但是也能通过测试),
因为String是不可变的对象,每次对String进行操作的时候,都会生成一个新的对象,这会对系统的性能造成影响。
而StringBuilder是对本身进行操作的。
public int uniqueMorseRepresentations(String[] words) {
HashSet<String> set = new HashSet<>();
String[] codes = new String[]{
".-","-...","-.-.","-..",".","..-.","--.","....","..",".---",
"-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-",
"..-","...-",".--","-..-","-.--","--.."
};
for(String word : words) {
StringBuilder code = new StringBuilder();
for(int i = 0; i < word.length(); i++) {
int idx = word.charAt(i) - 'a';
code.append(codes[idx]);
}
set.add(code.toString());
}
return set.size();
}