804. Unique Morse Code Words

Description

International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on.

For convenience, the full table for the 26 letters of the English alphabet is given below:

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cba" can be written as "-.-..--...", (which is the concatenation "-.-." + "-..." + ".-"). We'll call such a concatenation, the transformation of a word.

Return the number of different transformations among all words we have.

Example:

Input: words = ["gin", "zen", "gig", "msg"]
Output: 2
Explanation: 
The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."

There are 2 different transformations, "--...-." and "--...--.".

分析:

  1. 将每一个字符串都转化为摩斯密码;
  2. 使用set去重,返回摩斯密码个数(size());
class Solution {
    public int uniqueMorseRepresentations(String[] words) {
        String[] code = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};// store the morse code of 'a' ~ 'z'
        Set<String> morseSet = new HashSet<>();// 去重计算个数
        for(String word: words){
            char[] chars = word.toCharArray();// String转化为字符数组
            String morse = "";
            for(char c: chars){// 对于字符数组的每一个字符,Morse+该字符的Morsecode
                morse += code[c - 'a'];
            }
            morseSet.add(morse);// 该字符串的Morse code如set
        }
        
        return morseSet.size();
    }
}
原文地址:https://www.cnblogs.com/zhuobo/p/10602729.html