Skip to content

804. Unique Morse Code Words

  • Time: $O(\Sigma |\texttt{words[i]}|)$
  • Space: $O(|\texttt{words}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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)