Solution 1 - Optimized
Translate every word and count distinct Morse representations.
Translate every word and count distinct Morse representations.
class Solution:
def uniqueMorseRepresentations(self,words):
m=".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..".split()
return len({"".join(m[ord(c)-97] for c in w) for w in words})
if __name__ == "__main__": assert Solution().uniqueMorseRepresentations(["gin","zen","gig","msg"])==2const M:string[]=".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..".split(" ");class Solution{uniqueMorseRepresentations(w:string[]):number{return new Set(w.map(s=>[...s].map(c=>M[c.charCodeAt(0)-97]).join(""))).size;}}console.assert(new Solution().uniqueMorseRepresentations(["gin","zen","gig","msg"])===2);package main
import "fmt"
var m=[]string{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}
func unique(w []string)int{s:=map[string]bool{};for _,x:=range w{z:="";for _,c:=range x{z+=m[c-'a']};s[z]=true};return len(s)}
func main(){fmt.Println(unique([]string{"gin","zen","gig","msg"}))}use std::collections::HashSet;fn unique(ws:Vec<&str>)->usize{let m=".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..".split_whitespace().collect::<Vec<_>>();ws.into_iter().map(|w|w.bytes().map(|c|m[(c-b'a')as usize]).collect::<String>()).collect::<HashSet<_>>().len()}fn main(){assert_eq!(unique(vec!["gin","zen","gig","msg"]),2);}