804. 唯一摩尔斯密码词

题目

国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: “a” 对应 “.-“, “b” 对应 "-...", "c" 对应 "-.-.", 等等。

为了方便,所有26个英文字母对应摩尔斯密码表如下:

1
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,”cab” 可以写成 “-.-.-….-“,(即 “-.-.” + “-…” + “.-“字符串的结合)。我们将这样一个连接过程称作单词翻译。
返回我们可以获得所有词不同单词翻译的数量。

1
2
3
4
5
6
7
8
9
10
11
例如:
输入: words = ["gin", "zen", "gig", "msg"]
输出: 2
解释:
各单词翻译如下:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."

共有 2 种不同翻译, "--...-." 和 "--...--.".

提示:

  • 单词列表words 的长度不会超过 100
  • 每个单词 words[i]的长度范围为 [1, 12]
  • 每个单词 words[i]只包含小写字母。

解法

解法一:

转换,去重

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
private void init(Map<Character, String> map) {
String[] mos = new String[] {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
int i = 0;
for (char c = 'a'; c <= 'z';c++) {
map.put(c, mos[i++]);
}
}

private String getWordMos(Map<Character, String> map, String word) {
StringBuilder sb = new StringBuilder();
for (int i = 0;i < word.length();i++) {
sb.append(map.get(word.charAt(i)));
}
return sb.toString();
}

public int uniqueMorseRepresentations(String[] words) {
Map<Character, String> map = new HashMap<>();
init(map);
HashSet<String> set = new HashSet<>();
for(String s : words) {
set.add(getWordMos(map, s));
}
return set.size();
}
}
0%