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 words will be at most 100.
Each words[i] will have length in range [1, 12].
words[i] will only consist of lowercase letters.
题意:
将几个单词转换成摩斯码,返回不同摩斯码的数量
思路:
存储摩斯码,每个单词的每个字母通过ASC2码用当前字母-'a’可以对应摩斯码的位置,将摩斯码append成单词,将单词存入HashSet,因为HashSet不允许重复,直接返回长度
知识点:
String[]
数组的赋值是{} 不是[]
调用时是String[]
不是{}- new HashSet的时候可以不定义长度
- foreach中
String
类型第一个字母大写,String 才是指 java.lang.String 类
foreach中char
类型 - String转换为char :
使用String.charAt(index)
(返回值为char)可以得到String中某一指定位置的char。
使用String.toCharArray()
返回值为char[])可以得到将包含整个String的char数组。这样我们就能够使用从0开始的位置索引来访问string中的任意位置的元素。 - ASC2码小写字母位置是连续的,所以 ‘字母’-’a’=字母和a的距离,此题就对应morse数组中对应字母的索引
- HashSet中添加元素用
add()
,计算长度用size()
Bug:
此题中HashSet()是String类型,所以最后使用add方法时要先用toString()将StringBuilder()转换String类型才能使用
class Solution {
public int uniqueMorseRepresentations(String[] words) {
String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};//{} not[]
Set<String> ans = new HashSet<>();//words.length
//String[] arr = (String[])set.toArray(new String[0]);
for(String word:words){
// word.toCharArray()
StringBuilder res = new StringBuilder();
for(char c : word.toCharArray()){
res.append(morse[c-'a']);//[] not()
}
ans.add(res.toString());//tostring
}
return ans.size();
}
}