Translate each letter through a fixed table, concatenate each word's code, and insert it into a set.
Complexity
O(total characters) time and O(w) stored encodings.
Count distinct Morse encodings produced by a list of lowercase words.
Translate each letter through a fixed table, concatenate each word's code, and insert it into a set.
O(total characters) time and O(w) stored encodings.
package main
import "strings"
func uniqueMorseRepresentations(words []string) int {
codes := []string{".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}
seen := map[string]bool{}
for _, word := range words {
var encoded strings.Builder
for _, letter := range word {
encoded.WriteString(codes[letter-'a'])
}
seen[encoded.String()] = true
}
return len(seen)
}
class Solution:
def uniqueMorseRepresentations(self, words: list[str]) -> int:
codes = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
return len({"".join(codes[ord(letter) - ord("a")] for letter in word) for word in words})
function uniqueMorseRepresentations(words: string[]): number {
const codes = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."];
return new Set(words.map((word) => [...word].map((letter) => codes[letter.charCodeAt(0) - 97]).join(""))).size;
}