|
| 1 | +/****************************** |
| 2 | +804. Unique Morse Code Words |
| 3 | +International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, |
| 4 | +as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on. |
| 5 | +For convenience, the full table for the 26 letters of the English alphabet is given below: |
| 6 | +[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--", |
| 7 | +"-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] |
| 8 | +Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. |
| 9 | +For example, "cba" can be written as "-.-..--...", (which is the concatenation "-.-." + "-..." + ".-"). |
| 10 | +We'll call such a concatenation, the transformation of a word. |
| 11 | +Return the number of different transformations among all words we have. |
| 12 | + |
| 13 | +Example: |
| 14 | +Input: words = ["gin", "zen", "gig", "msg"] |
| 15 | +Output: 2 |
| 16 | +Explanation: |
| 17 | +The transformation of each word is: |
| 18 | +"gin" -> "--...-." |
| 19 | +"zen" -> "--...-." |
| 20 | +"gig" -> "--...--." |
| 21 | +"msg" -> "--...--." |
| 22 | +There are 2 different transformations, "--...-." and "--...--.". |
| 23 | + |
| 24 | +Note: |
| 25 | +The length of words will be at most 100. |
| 26 | +Each words[i] will have length in range [1, 12]. |
| 27 | +words[i] will only consist of lowercase letters. |
| 28 | +******************************/ |
| 29 | + |
| 30 | + |
| 31 | +class Solution { |
| 32 | + public int uniqueMorseRepresentations(String[] words) { |
| 33 | + String [] morseCodes = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--", |
| 34 | + "-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; |
| 35 | + HashSet<String> set = new HashSet<>(); |
| 36 | + |
| 37 | + for(String x : words) { |
| 38 | + String result = ""; |
| 39 | + |
| 40 | + for(char c : x.toCharArray()) { |
| 41 | + result = result + morseCodes[c - 'a']; |
| 42 | + } |
| 43 | + |
| 44 | + set.add(result); |
| 45 | + } |
| 46 | + |
| 47 | + return set.size(); |
| 48 | + } |
| 49 | +} |
0 commit comments