Leetcode 804. Unique Morse Code Words
The problem is to determine the number of unique Morse code transformations among a list of words. Each letter in a word can be transformed into its corresponding Morse code representation. The Morse code for each letter is given by a predefined table:
"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 a list of words, you need to find out how many different transformations there are.
#include <iostream>
#include <vector>
#include <unordered_set>
#include <string>
std::string morseMapping[26] = {
".-","-...","-.-.","-..",".","..-.",
"--.","....","..",".---","-.-",".-..",
"--","-.","---",".--.","--.-",".-.",
"...","-","..-","...-",".--","-..-",
"-.--","--.."
};
int uniqueMorseRepresentations(const std::vector<std::string>& words) {
std::unordered_set<std::string> uniqueTransformations;
for (const auto& word : words) {
std::string morseWord;
for (char c : word) {
morseWord += morseMapping[c - 'a'];
}
uniqueTransformations.insert(morseWord);
}
return uniqueTransformations.size();
}
int main() {
std::vector<std::string> words = {"gin", "zen", "gig", "msg"};
std::cout << "Number of unique Morse code transformations: "
<< uniqueMorseRepresentations(words) << std::endl;
return 0;
}
N
is the number of words and M
is the average length of each word. This covers the iteration through each word and through each character in the word to form the Morse code transformation.This solution leverages the simplicity and uniqueness properties of sets to efficiently determine the number of unique Morse code transformations.
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?