標籤:col das length cab nsf nes form stand pen
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cab" can be written as "-.-.-....-", (which is the concatenation "-.-." + "-..." + ".-"). We‘ll call such a concatenation, the transformation of a word.
Return the number of different transformations among all words we have.
Example:Input: words = ["gin", "zen", "gig", "msg"]Output: 2Explanation: The transformation of each word is:"gin" -> "--...-.""zen" -> "--...-.""gig" -> "--...--.""msg" -> "--...--."There are 2 different transformations, "--...-." and "--...--.".
1 //Time O(n), Space O(n) HashSet 用來去除重複 2 3 public int uniqueMorseRepresentations(String[] words) { 4 String[] map = new String[]{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; 5 6 if (words == null || words.length == 0) { 7 return 0; 8 } 9 10 HashSet<String> result = new HashSet<String>();11 12 for (String word : words) {13 StringBuilder sb = new StringBuilder();14 15 for (int i = 0; i < word.length(); i++) {16 int loc = word.charAt(i) - ‘a‘;17 sb.append(map[loc]);18 }19 20 result.add(sb.toString());21 }22 23 return result.size();24 }
804. Unique Morse Code Words