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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章