
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.
1using System;
2using System.Collections.Generic;
3
4class UniqueMorseCode {
5 public static int UniqueMorseRepresentations(string[] words) {
6 string[] morseMap = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
7 HashSet<string> uniqueTransformations = new HashSet<string>();
8 foreach (string word in words) {
9 string transformation = "";
10 foreach (char c in word) {
11 transformation += morseMap[c - 'a'];
12 }
13 uniqueTransformations.Add(transformation);
14 }
15 return uniqueTransformations.Count;
16 }
17
18 static void Main() {
19 string[] words = { "gin", "zen", "gig", "msg" };
20 Console.WriteLine(UniqueMorseRepresentations(words));
21 }
22}In C#, we apply a similar logic using a HashSet to track unique transformations. For each word, its transformation is computed and added to the set. The final count of unique transformations is determined by the set's size.
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 Python function substitutes quickly, embracing ASCII logic to convert word characters into Morse, employing set() to deftly filter duplicates.