1、国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: "a"
对应 ".-"
, "b"
对应 "-..."
, "c"
对应 "-.-."
, 等等。
为了方便,所有26个英文字母对应摩尔斯密码表如下:
1 [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,"cab" 可以写成 "-.-..--...",(即 "-.-." + "-..." + ".-"字符串的结合)。我们将这样一个连接过程称作单词翻译。
返回我们可以获得所有词不同单词翻译的数量。
1 例如:
2 输入: words = ["gin", "zen", "gig", "msg"]
3 输出: 2
4 解释:
5 各单词翻译如下:
6 "gin" -> "--...-."
7 "zen" -> "--...-."
8 "gig" -> "--...--."
9 "msg" -> "--...--."
10
11 共有 2 种不同翻译, "--...-." 和 "--...--.".
注意:
words
的长度不会超过 100
。words[i]
的长度范围为 [1, 12]
。words[i]
只包含小写字母。2、具体的代码实现逻辑,如下所示:
1 package com.leetcode;
2
3 import java.util.TreeSet;
4
5 /**
6 * @ProjectName: dataConstruct
7 * @Package: com.leetcode
8 * @ClassName: MorseRepresentations
9 * @Author: biehl
10 * @Description: ${description}
11 * @Date: 2020/3/14 13:11
12 * @Version: 1.0
13 */
14 public class MorseRepresentations {
15
16
17 /**
18 * 给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。
19 * 例如,"cab" 可以写成 "-.-..--...",(即 "-.-." + "-..." + ".-"字符串的结合)。
20 * 我们将这样一个连接过程称作单词翻译。
21 *
22 * @param words
23 * @return
24 */
25 public int uniqueMorseRepresentations(String[] words) {
26 // 为了方便,所有26个英文字母对应摩尔斯密码表如下:
27 String[] codes = new String[]{".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
28 // 声明一个变量
29 TreeSet<String> treeSet = new TreeSet<String>();
30 // 循环遍历单词数组
31 for (String word : words) {
32 // 声明一个字符串变量
33 StringBuilder stringBuilder = new StringBuilder();
34 for (int i = 0; i < word.length(); i++) {
35 // 可以获取到小写字母的索引位置
36 System.out.println(word.charAt(i) - 'a');
37 stringBuilder.append(codes[word.charAt(i) - 'a']);
38 }
39
40 treeSet.add(stringBuilder.toString());
41 }
42 return treeSet.size();
43 }
44
45 public static void main(String[] args) {
46 String[] words = new String[]{"gin", "zen", "gig", "msg"};
47 MorseRepresentations morseRepresentations = new MorseRepresentations();
48 int res = morseRepresentations.uniqueMorseRepresentations(words);
49 System.out.println(res);
50 }
51
52 }