LeetCode804. 唯一摩尔斯密码词(集合的应用)

804. 唯一摩尔斯密码词

LeetCode第804号问题,题目链接:https://leetcode-cn.com/problems/unique-morse-code-words/

国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: “a” 对应 “.-”, “b” 对应 “-…”, “c” 对应 “-.-.”, 等等。
为了方便,所有26个英文字母对应摩尔斯密码表如下:
[".-","-…","-.-.","-…",".","…-.","–.","…","…",".—","-.-",".-…","–","-.","—",".–.","–.-",".-.","…","-","…-","…-",".–","-…-","-.–","–…"]
给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合。例如,“cab” 可以写成 “-.-…–…”,(即 “-.-.” + “-…” + ".-"字符串的结合)。我们将这样一个连接过程称作单词翻译。
返回我们可以获得所有词不同单词翻译的数量。
例如:
输入: words = [“gin”, “zen”, “gig”, “msg”]
输出: 2
解释:
各单词翻译如下:
“gin” -> “–…-.”
“zen” -> “–…-.”
“gig” -> “–…--.”
“msg” -> “–…--.”
共有 2 种不同翻译, “–…-.” 和 “–…--.”.

题解: 将words字符串遍历按照密码表生成word对应的摩斯密码存进集合中,由于集合无法存储重复数据,直接返回集合的大小size。
使用Java提供的标准库TreeSet

import java.util.TreeSet;

class Solution {
    public int uniqueMorseRepresentations(String[] words) {

        // String类型的数组中有26个英文字母对应的密码
        String[] codes = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
                "....", "..", ".---", "-.-", ".-..", "--", "-.",
                "---", ".--.", "--.-", ".-.", "...", "-", "..-",
                "...-", ".--", "-..-", "-.--", "--.."};

        TreeSet<String> set = new TreeSet();

        // 遍历一变words数组
        for (String word : words) {

            StringBuilder res = new StringBuilder();
            // 对word的进行遍历 经过循环在res中存储了word对应的摩斯码
            for (int i = 0; i < word.length(); i++) {
                // 获得当前字母进行偏移
                res.append(codes[word.charAt(i) - 'a']);
            }

            // 存进集合set中 在添加的过程中,如果两个单词摩斯码相同,集合自动忽略重复
            set.add(res.toString());
        }
        return set.size();
    }

	// 进行本地测试
    public static void main(String[] args) {
        String[] words = {"gin", "zen", "gig", "msg"};
        int res = new Solution().uniqueMorseRepresentations(words);
        System.out.println(res);
    }

}

猜你喜欢

转载自blog.csdn.net/wankcn/article/details/106340647