英文题目:
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, "cba" 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
words
will be at most100
.- Each
words[i]
will have length in range[1, 12]
.words[i]
will only consist of lowercase letters.
中文题目解释:
国际摩尔斯电码规定了一种标准编码,其中每个字母映射到一系列点和短划线,如下所示:
"a"
映射到".-"
,"b"
映射到"-..."
,"c"
映射到"-.-."
等等。为方便起见,下面给出了英文字母26个字母的完整表格:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,"cab" 可以写成 "-.-..--...",(即 "-.-." + "-..." + ".-"字符串的结合)。我们将这样一个连接过程称作单词翻译。
返回我们可以获得所有词不同单词翻译的数量。
例子:
输入: words = ["gin", "zen", "gig", "msg"]
输出: 2
解释:
各单词翻译如下:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."共有 2 种不同翻译, "--...-." 和 "--...--."
注意:
- 长度
words
最多100
。- 每个
words[i]
都有长度范围[1, 12]
。words[i]
只会包含小写字母。
解析:
利用Set集合中保证对象唯一的特点,则只需要将字符串转换为标准编码后置入Set集合中,然后返回Set集合中的对象个数即可
提交结果:
class Solution {
static String[] s={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
public int uniqueMorseRepresentations(String[] words) {
Set<String> result=new HashSet<>();
for (String word:words) {
result.add(getString(word));
}
return result.size();
}
public String getString(String word){
StringBuilder sb=new StringBuilder();
for(char x:word.toCharArray()){
sb.append(s[x-'a']);
}
return sb.toString();
}
}