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.