Leetcode 804. Unique Morse Code Words
The problem states that we are given an array of words, where each word can be converted into a Morse code string based on the given mapping of each letter to a Morse code character. Our task is to determine how many different Morse code transformations we can get from the given array of words.
Each letter has a corresponding Morse code and the mapping is as follows:
'a' -> ".-"
'b' -> "-..."
'c' -> "-.-."
'd' -> "-.."
'e' -> "."
'f' -> "..-."
'g' -> "--."
'h' -> "...."
'i' -> ".."
'j' -> ".---"
'k' -> "-.-"
'l' -> ".-.."
'm' -> "--"
'n' -> "-."
'o' -> "---"
'p' -> ".--."
'q' -> "--.-"
'r' -> ".-."
's' -> "..."
't' -> "-"
'u' -> "..-"
'v' -> "...-"
'w' -> ".--"
'x' -> "-..-"
'y' -> "-.--"
'z' -> "--.."
Given words, we need to return the number of unique Morse code transformations among them.
words
.HashSet
to keep track of unique Morse code transformations as sets inherently ignore duplicates.import java.util.HashSet;
import java.util.Set;
public class UniqueMorseCodeWords {
public int uniqueMorseRepresentations(String[] words) {
// Morse code for each letter a-z
String[] morseCodes = new String[]{
".-","-...","-.-.","-..",".","..-.",
"--.","....","..",".---","-.-",".-..",
"--","-.","---",".--.","--.-",".-.",
"...","-","..-","...-",".--","-..-",
"-.--","--.."
};
// Using a HashSet to keep track of unique morse transformations
Set<String> uniqueTransformations = new HashSet<>();
// Iterate through each word
for (String word : words) {
StringBuilder transformation = new StringBuilder();
// Convert each character to its corresponding morse code
for (char c : word.toCharArray()) {
transformation.append(morseCodes[c - 'a']);
}
// Add the transformation to the set
uniqueTransformations.add(transformation.toString());
}
// The number of unique transformations
return uniqueTransformations.size();
}
// Example usage
public static void main(String[] args) {
UniqueMorseCodeWords solution = new UniqueMorseCodeWords();
String[] words = {"gin", "zen", "gig", "msg"};
System.out.println(solution.uniqueMorseRepresentations(words)); // Output: 2
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?