LeetCode 题目地址
描述
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 "--...--.".
Note:
- The length of
wordswill be at most100. - Each
words[i]will have length in range[1, 12]. words[i]will only consist of lowercase letters.
题目大意是,给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,"cab" 可以写成 "-.-.-....-",(即 "-.-." + "-..." + ".-"字符串的结合)。求一组字符串中有多少不同的摩尔斯密码组合。
解决方法
利用 char 字符的减法运算来获取每个英文字符对应的摩尔斯密码,然后进行组合。Set 的特点是不可重复,所以可用 Set 对象存放每组摩尔斯密码,返回 Set 对象的大小即可。
public int uniqueMorseRepresentations(String[] words){
if(words == null || words.length == 0){
return 0;
}
String[] table = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
Set<String> set = new HashSet();
for(String word : words){
char[] chars = word.toCharArray();
StringBuilder morse = new StringBuilder();
for(char c : chars){
morse.append(table[c-'a']);
}
set.add(morse.toString());
}
return set.size();
}