
Sponsored
Sponsored
We can utilize a HashSet data structure to store the unique transformations. For each word, we can generate its Morse code transformation by replacing each character by its corresponding Morse code. We then add each transformation to the HashSet to automatically handle duplicates. The size of the HashSet at the end gives us the number of unique transformations.
Time Complexity: O(N), where N is the total number of characters across all words.
Space Complexity: O(WL), where W is the number of words and L is the length of the longest word, due to storing transformations.
1import java.util.HashSet;
2import java.util.Set;
3
4public class UniqueMorseCode {
5 public static int uniqueMorseRepresentations(String[] words) {
6 String[] morseMap = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
7 Set<String> uniqueTransformations = new HashSet<>();
8 for (String word : words) {
9 StringBuilder transformation = new StringBuilder();
10 for (char c : word.toCharArray()) {
11 transformation.append(morseMap[c - 'a']);
12 }
13 uniqueTransformations.add(transformation.toString());
14 }
15 return uniqueTransformations.size();
16 }
17
18 public static void main(String[] args) {
19 String[] words = {"gin", "zen", "gig", "msg"};
20 System.out.println(uniqueMorseRepresentations(words));
21 }
22}The Java approach is similar to the C++ one. We use a HashSet to store unique transformations. Each word is converted into its Morse code representation by mapping each character, and this transformation is added to the set. Finally, the size of the set tells us the number of unique transformations.
In this method, we establish a direct mapping of characters to Morse code using a fixed array index, which simplifies the translation process by utilizing the ASCII value difference between 'a' and the current character. We then use the translated words to populate a set directly, ensuring uniqueness of each transformation.
Time Complexity: O(N^2), due to checking each transformation against existing ones in the list.
Space Complexity: O(WL), where W is the word count and L is the length of the longest word, needed to store transformations.
This Java method directly transforms from character indices, neatly leveraging a HashSet to avoid duplicates. It conveys simplicity via straightforward ASCII operations to access Morse maps.