题目
类型:数组
解题思路
将数组 words 中的每个单词按照莫尔斯密码表转换为摩尔斯码,并加入哈希集合中,哈希集合中元素的个数即为最终的答案
代码
class Solution {
public static final String[] MORSE = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--.."};
public int uniqueMorseRepresentations(String[] words) {
Set<String> seen = new HashSet<String>();
for (String word : words) {
StringBuilder code = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
code.append(MORSE[c - 'a']);
}
seen.add(code.toString());
}
return seen.size();
}
}