Unique Morse Code Words


  • 0

    Click here to see the full article post


  • 0
    P
    class Solution {
        public int uniqueMorseRepresentations(String[] words) {
         
            Map<Character,String> map = new HashMap<>();
            map.put('a',".-");
            map.put('b',"-...");
            map.put('c',"-.-.");
            map.put('d',"-..");
            map.put('e',".");
            map.put('f',"..-.");
            map.put('g',"--.");
            map.put('h',"....");
            map.put('i',"..");
            map.put('j',".---");
            map.put('k',"-.-");
            map.put('l',".-..");
            map.put('m',"--");
            map.put('n',"-.");
            map.put('o',"---");
            map.put('p',".--.");
            map.put('q',"--.-");
            map.put('r',".-.");
            map.put('s',"...");
            map.put('t',"-");
            map.put('u',"..-");
            map.put('v',"...-");
            map.put('w',".--");
            map.put('x',"-..-");
            map.put('y',"-.--");
            map.put('z',"--..");
            
            Set<String> set = new HashSet<>();
            for (String str : words){
                String temp = str;
                String morseStr = "";
                for (int i=0;i<temp.length();i++){                
                    morseStr = morseStr + map.get(temp.charAt(i));                
                }
                System.out.println(morseStr);
                set.add(morseStr);
                
            }
            
            return set.size();
                                    
        }
    }
    

  • 0
    A
    class Solution {
        public int uniqueMorseRepresentations(String[] words) {
            String morse[]={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
            HashSet<String> set=new HashSet();
            for (String s:words){
                set.add(func(morse,s));
            }
            
            return set.size();
        }
        
        String func(String m[],String s){
            StringBuilder ss=new StringBuilder();
            for (char c:s.toCharArray()){
                ss.append(m[c-97]);
            }
            return ss.toString();
        }
    }
    

  • 0
    W
    var uniqueMorseRepresentations = function(words) {
        const set = []
        const alpha = [".-","-...","-.-.","-..",".","..-.",
                               "--.","....","..",".---","-.-",".-..",
                               "--","-.","---",".--.","--.-",".-.",
                               "...","-","..-","...-",".--","-..-","-.--","--.."]
        
        words.forEach(word => {
            const morse = [];
            [...word].forEach(letter => {
                morse.push(alpha[letter.charCodeAt(0) - 97])
            })
            !set.includes(morse.join('')) ? set.push(morse.join('')) : null 
        })
        
        return set.length
    };
    

    Naive - o(n^2)


  • 0
    M
    This post is deleted!

  • 0
    M

    with Java Streams:

    class Solution {
        String[] morse = new String[]{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        public int uniqueMorseRepresentations(String[] words) {
            return (int) Arrays.stream(words)
                .map(word -> word.chars()
                                 .mapToObj(c -> morse[c - 'a'])
                                 .collect(Collectors.joining())
                .distinct()
                .count();
        }
    }
    

  • 0
    T

    Here is my accepted solution:

    public int uniqueMorseRepresentations(String[] words) {
            
            String[] morseCodes = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
            
            HashSet<String> set = new HashSet<>();
            
            for(String word: words){
                char[] c = word.toCharArray();
                String morsed = "";
                for(char ch : c){
                    morsed += morseCodes[ch - 'a'];
                }
                set.add(morsed);
            }
            
            return set.size();
        }
    
    

  • 0
    J

    Accepted C# solution:

    public int UniqueMorseRepresentations(string[] words)
    {
    string[] values = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };

            List<string> moreStrList = new List<string>();
            StringBuilder tempStringBuilder = new StringBuilder();
    
            for (int i = 0; i < words.Length; i++)
            {
                for (int j = 0; j < words[i].Length; j++)
                {
                    tempStringBuilder.Append(values[(words[i])[j] - 'a']);
                }
    
                Console.WriteLine(words[i] + "-->" + tempStringBuilder.ToString());
    
                if (!moreStrList.Contains(tempStringBuilder.ToString()))
                {
                    moreStrList.Add(tempStringBuilder.ToString());
                    
                }
                tempStringBuilder.Clear();
            }
            return moreStrList.Count;
        }

  • 0
    D

    class Solution {
    companion object {
    @JvmStatic
    val morses = arrayOf(".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..")
    }

    fun uniqueMorseRepresentations(words: Array<String>): Int =
        HashSet(words.map { it.map { morses[it.toInt() - 'a'.toInt()] }.joinToString(separator = "") }).count()
    

    }


  • 0
    H
    func uniqueMorseRepresentations(words []string) int {
    	morseCodes := []string{".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}
    	cnt := make(map[string]int)
    	for _, word := range words {
    		tmp := ""
    		for _, alpha := range word {
    			tmp += morseCodes[alpha-97]
    		}
    		if _, ok := cnt[tmp]; !ok {
    			cnt[tmp] = 1
    		}
    	}
    
    	return len(cnt)
    }
    

  • 0
    P

    from string import ascii_lowercase
    class Solution:
    def uniqueMorseRepresentations(self, words):
    morse_code = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
    li = list()
    for word in words:
    t = ""
    for i in word:
    t += morse_code[ascii_lowercase.index(i)]
    li.append(t)
    return len(set(li))


  • 0
    H

    '''
    class Solution {
    public int uniqueMorseRepresentations(String[] words) {
    String[] morseCode = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
    int alphabetIter = 0;
    Map <Character,String>morseLookup = new HashMap<Character,String>();
    for(char alphabet = 'a';alphabet<='z';alphabet++){
    morseLookup.put(alphabet,morseCode[alphabetIter]);
    alphabetIter++;
    }
    HashSet <String>transform = new HashSet<String>();
    for(String word : words){
    StringBuilder wordTrans = new StringBuilder();
    for(int i=0;i<word.length();i++){
    wordTrans.append(morseLookup.get(word.charAt(i)));
    }
    transform.add(wordTrans.toString());
    }
    return transform.size();
    }

    }

    '''


  • 0
    K

    class Solution {
    public int uniqueMorseRepresentations(String[] words) {
    String[] morsecodes = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..",
    "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-",
    ".--", "-..-", "-.--", "--.."};

        Set<String> result = new TreeSet<>();
    
        for (String str: words) {
            char[] buff = str.toCharArray();
            StringBuilder sb = new StringBuilder("");
            for (char ch: buff){
                sb.append(morsecodes[ch - 97]) ;
            }
    
            result.add(sb.toString());
        }
        return result.size();
    }
    

    }


  • 0
    X
    int uniqueMorseRepresentations(vector<string>& words) {
        static const string morse[] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        set<string> cnt;
        for (size_t i = 0; i < words.size(); ++ i) {
            string tmp;
            for (size_t j = 0; j <  words[i].length(); ++ j) {
                tmp += morse[words[i][j]-'a'];
            }
            cnt.insert(tmp);
        }
        return cnt.size();
    }
    

  • 0
    Z
    This post is deleted!

  • 0
    Z
    public int uniqueMorseRepresentations(String[] words) {
         String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        HashSet<String> set = new HashSet<String>();
        for (int i=0; i<words.length; i++) {
            String morse_s = "";
            for(char s: words[i].toCharArray()) {
                morse_s += morse[s - 'a'];
            }
            set.add(morse_s);
        }
        return set.size();
    }

  • 0
    D

    class Solution {
    public:
    int uniqueMorseRepresentations(const vector<string>& words) {
    const vector<string> morse_code = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
    set <string> transformations = {};
    for (const string & word : words)
    {
    string transformed_word = "";
    for (const char & c : word)
    transformed_word += morse_code[c - 'a'];
    transformations.insert(transformed_word);
    }
    return transformations.size();
    }

    };


  • 0
    S

    class Solution {
    public:
    int uniqueMorseRepresentations(vector<string>& words) {
    vector<string> morseVect = {".-","-...","-.-.","-..",".","..-.","--.",
    "....","..",".---","-.-",".-..","--","-.",
    "---",".--.","--.-",".-.","...","-","..-",
    "...-",".--","-..-","-.--","--.."};
    int num;
    set<string> morseSet;
    for(auto& str : words)
    {
    string morseStr;
    for(auto i : str)
    {
    morseStr += morseVect[i - 97];
    }
    if(!morseStr.empty())
    {
    morseSet.insert(morseStr);
    }
    }
    return morseSet.size();
    }
    };


  • 0
    Y

    MORSE[c - 'a'] can someone explain this ??.. I didn't understand the logic


  • 0
    S

    @yuarajsanthosh
    String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};

    morse code of 'a' is morse[0], use c-'a' as the index in morse tab to get the 'a' morse code


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.