美文网首页
Leetcode - 804. Unique Morse Cod

Leetcode - 804. Unique Morse Cod

作者: 肚子糖 | 来源:发表于2018-10-06 13:10 被阅读0次

Morse Code

This program aims to transfer characters to morse code. It will read in a word String array and then return the number of different transformations among all words.

My solution

class Solution {
    public int uniqueMorseRepresentations(String[] words) {
        HashMap<Character, String> hashMap = new HashMap<Character, String>();
        hashMap.put('a', ".-");
        hashMap.put('b', "-...");
        hashMap.put('c', "-.-.");
        hashMap.put('d', "-..");
        hashMap.put('e', ".");
        hashMap.put('f', "..-.");
        hashMap.put('g', "--.");
        hashMap.put('h', "....");
        hashMap.put('i', "..");
        hashMap.put('j', ".---");
        hashMap.put('k', "-.-");
        hashMap.put('l', ".-..");
        hashMap.put('m', "--");
        hashMap.put('n', "-.");
        hashMap.put('o', "---");
        hashMap.put('p', ".--.");
        hashMap.put('q', "--.-");
        hashMap.put('r', ".-.");
        hashMap.put('s', "...");
        hashMap.put('t', "-");
        hashMap.put('u', "..-");
        hashMap.put('v', "...-");
        hashMap.put('w', ".--");
        hashMap.put('x', "-..-");
        hashMap.put('y', "-.--");
        hashMap.put('z', "--..");
        
        List<String> morseList = new ArrayList<String>();
        for(int i = 0; i < words.length; i++) {
            String str = "";
            String word = words[i];
            for(int j = 0; j < word.length(); j++)
                str += (hashMap.get(word.charAt(j)));
            System.out.println("\"" + word + "\"" + " -> " + "\"" + str + "\"");
            if (!morseList.contains(str))
                morseList.add(str);
        }
        return morseList.size();
    }
}

Official solution

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

        Set<String> seen = new HashSet();
        for (String word: words) {
            StringBuilder code = new StringBuilder();
            for (char c: word.toCharArray())
                code.append(MORSE[c - 'a']);
            seen.add(code.toString());
        }

        return seen.size();
    }
}

Summary

  • The connection between the 26 letters of the English alphabet and the MORSE array could be MORSE[characer - 'a'];
  • Use Set to differentiate its elements, so ArrayList here is unnecessary.

相关文章

网友评论

      本文标题:Leetcode - 804. Unique Morse Cod

      本文链接:https://www.haomeiwen.com/subject/kichaftx.html