题目

类型:数组

image.png

解题思路

将数组 words 中的每个单词按照莫尔斯密码表转换为摩尔斯码,并加入哈希集合中,哈希集合中元素的个数即为最终的答案

代码

  1. class Solution {
  2. public static final String[] MORSE = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
  3. "....", "..", ".---", "-.-", ".-..", "--", "-.",
  4. "---", ".--.", "--.-", ".-.", "...", "-", "..-",
  5. "...-", ".--", "-..-", "-.--", "--.."};
  6. public int uniqueMorseRepresentations(String[] words) {
  7. Set<String> seen = new HashSet<String>();
  8. for (String word : words) {
  9. StringBuilder code = new StringBuilder();
  10. for (int i = 0; i < word.length(); i++) {
  11. char c = word.charAt(i);
  12. code.append(MORSE[c - 'a']);
  13. }
  14. seen.add(code.toString());
  15. }
  16. return seen.size();
  17. }
  18. }