804. Unique Morse Code Words

Posted jessie2009

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了804. Unique Morse Code Words相关的知识,希望对你有一定的参考价值。

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, "cab" 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 //Time O(n), Space O(n) HashSet 用来去除重复
 2 
 3     public int uniqueMorseRepresentations(String[] words) {
 4         String[] map = new String[]{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
 5 
 6         if (words == null || words.length == 0) {
 7             return 0;
 8         }
 9         
10         HashSet<String> result = new HashSet<String>();
11         
12         for (String word : words) {
13             StringBuilder sb = new StringBuilder();
14             
15             for (int i = 0; i < word.length(); i++) {
16                 int loc = word.charAt(i) - ‘a‘;
17                 sb.append(map[loc]);
18             }
19             
20             result.add(sb.toString());
21         }
22         
23         return result.size();
24     }

 

以上是关于804. Unique Morse Code Words的主要内容,如果未能解决你的问题,请参考以下文章

804. Unique Morse Code Words

804. Unique Morse Code Words

LeetCode 804. Unique Morse Code Words

leetcode-804-Unique Morse Code Words

LeetCode 804 Unique Morse Code Words 解题报告

Leetcode 804. Unique Morse Code Words