|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.HashSet; |
| 4 | +import java.util.Set; |
| 5 | + |
| 6 | +/** |
| 7 | + * 804. Unique Morse Code Words |
| 8 | +
|
| 9 | + 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. |
| 10 | +
|
| 11 | + For convenience, the full table for the 26 letters of the English alphabet is given below: |
| 12 | +
|
| 13 | + [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] |
| 14 | +
|
| 15 | + 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. |
| 16 | +
|
| 17 | + Return the number of different transformations among all words we have. |
| 18 | +
|
| 19 | + Example: |
| 20 | + Input: words = ["gin", "zen", "gig", "msg"] |
| 21 | + Output: 2 |
| 22 | + Explanation: |
| 23 | + The transformation of each word is: |
| 24 | + "gin" -> "--...-." |
| 25 | + "zen" -> "--...-." |
| 26 | + "gig" -> "--...--." |
| 27 | + "msg" -> "--...--." |
| 28 | +
|
| 29 | + There are 2 different transformations, "--...-." and "--...--.". |
| 30 | +
|
| 31 | + Note: |
| 32 | + The length of words will be at most 100. |
| 33 | + Each words[i] will have length in range [1, 12]. |
| 34 | + words[i] will only consist of lowercase letters. |
| 35 | + */ |
| 36 | +public class _804 { |
| 37 | + public static class Solution1 { |
| 38 | + public int uniqueMorseRepresentations(String[] words) { |
| 39 | + String[] morseCodes = |
| 40 | + new String[] {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", |
| 41 | + "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", |
| 42 | + ".--", "-..-", "-.--", "--.."}; |
| 43 | + Set<String> concatenation = new HashSet<>(); |
| 44 | + StringBuilder sb = new StringBuilder(); |
| 45 | + for (String word : words) { |
| 46 | + sb.setLength(0); |
| 47 | + for (char c : word.toCharArray()) { |
| 48 | + sb.append(morseCodes[c - 'a']); |
| 49 | + } |
| 50 | + concatenation.add(sb.toString()); |
| 51 | + } |
| 52 | + return concatenation.size(); |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments