LeetCode Solutions
804. Unique Morse Code Words
Time: $O(\Sigma |\texttt{words[i]}|)$ Space: $O(|\texttt{words}|)$
class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
const vector<string> morse{
".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
unordered_set<string> transformations;
for (const string& word : words) {
string transformation;
for (const char c : word)
transformation += morse[c - 'a'];
transformations.insert(transformation);
}
return transformations.size();
}
};
class Solution {
public int uniqueMorseRepresentations(String[] words) {
final String[] morse = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
Set<String> transformations = new HashSet<>();
for (final String word : words) {
StringBuilder transformation = new StringBuilder();
for (final char c : word.toCharArray())
transformation.append(morse[c - 'a']);
transformations.add(transformation.toString());
}
return transformations.size();
}
}
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
transformations = set()
for word in words:
transformation = ''.join(morse[ord(c) - ord('a')] for c in word)
transformations.add(transformation)
return len(transformations)