LeetCode 804 Unique Morse Code Words

题意

给予一个编码表,26 个字母分别对应一个编码,给定一组单词,获取单词的所有字母组合后的编码中不重复的数量。

解法

首先为每个单词的每个字符进行转码, 将转码后的数据放到 Set 集合中, 最后返回 Set 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
private String[] codes = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};

public int uniqueMorseRepresentations(String[] words) {
HashSet<String> hashSet = new HashSet<String>();
for (String word : words) {
hashSet.add(convertCode(word));
}
return hashSet.size();
}

private String convertCode(String word) {
char[] chars = word.toCharArray();

String code = "";
for (char ch : chars) {
code += codes[ch - 97];
}
return code;
}
}

Runtime: 4 ms, faster than 100.00% of Java online submissions for Unique Morse Code Words.

  • 本文作者: 赵俊
  • 本文链接: http://www.zhaojun.im/leetcode-804/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!