Unique Morse Code Words

easy hashing strings

Problem

Given a list of words, each letter is translated using a fixed Morse alphabet. The transformation of a word is the concatenation of its letters' Morse codes. Return the number of distinct transformations.

Inputwords = ["gin","zen","gig","msg"]
Output2
"gin" and "zen" share a transformation; so do "gig" and "msg".

def uniqueMorseRepresentations(words):
    morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
    seen = set()
    for w in words:
        seen.add(''.join(morse[ord(c) - ord('a')] for c in w))
    return len(seen)
var uniqueMorseRepresentations = function(words) {
    const morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."];
    const seen = new Set();
    for (const w of words) {
        let t = '';
        for (const c of w) t += morse[c.charCodeAt(0) - 97];
        seen.add(t);
    }
    return seen.size;
};
class Solution {
    public int uniqueMorseRepresentations(String[] words) {
        String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        java.util.Set<String> seen = new java.util.HashSet<>();
        for (String w : words) {
            StringBuilder sb = new StringBuilder();
            for (char c : w.toCharArray()) sb.append(morse[c - 'a']);
            seen.add(sb.toString());
        }
        return seen.size();
    }
}
class Solution {
public:
    int uniqueMorseRepresentations(vector<string>& words) {
        vector<string> morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        unordered_set<string> seen;
        for (auto& w : words) {
            string t;
            for (char c : w) t += morse[c - 'a'];
            seen.insert(t);
        }
        return seen.size();
    }
};
Time: O(N) Space: O(N)