天天看点

LeetCode 804 Unique Morse Code Words

题意

给予一个编码表,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.