LeetCode 804 Unique Morse Code Words

栏目: 编程工具 · 发布时间: 7年前

内容简介:给予一个编码表,26 个字母分别对应一个编码,给定一组单词,获取单词的所有字母组合后的编码中不重复的数量。首先为每个单词的每个字符进行转码, 将转码后的数据放到 Set 集合中, 最后返回 Set 的长度。

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

解法

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

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.

以上所述就是小编给大家介绍的《LeetCode 804 Unique Morse Code Words》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Programming Ruby

Programming Ruby

Dave Thomas、Chad Fowler、Andy Hunt / Pragmatic Bookshelf / 2004-10-8 / USD 44.95

Ruby is an increasingly popular, fully object-oriented dynamic programming language, hailed by many practitioners as the finest and most useful language available today. When Ruby first burst onto the......一起来看看 《Programming Ruby》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具