leetcode刷題記錄 easy(4) 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, "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 "--...--.".

Note:

  • The length of words will be at most 100.
  • Each words[i] will have length in range [1, 12].
  • words[i] will only consist of lowercase letters.

中文題目解釋:

國際摩爾斯電碼規定了一種標準編碼,其中每個字母映射到一系列點和短劃線,如下所示:"a"映射到".-""b"映射到"-...""c"映射到"-.-."等等。

爲方便起見,下面給出了英文字母26個字母的完整表格:

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

給定一個單詞列表,每個單詞可以寫成每個字母對應摩爾斯密碼的組合。例如,"cab" 可以寫成 "-.-..--...",(即 "-.-." + "-..." + ".-"字符串的結合)。我們將這樣一個連接過程稱作單詞翻譯。

返回我們可以獲得所有詞不同單詞翻譯的數量。

例子:
輸入: words = ["gin", "zen", "gig", "msg"]
輸出: 2
解釋: 
各單詞翻譯如下:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."

共有 2 種不同翻譯, "--...-." 和 "--...--." 

注意:

  • 長度words最多100
  • 每個words[i]都有長度範圍[1, 12]
  • words[i] 只會包含小寫字母。

解析:

利用Set集合中保證對象唯一的特點,則只需要將字符串轉換爲標準編碼後置入Set集合中,然後返回Set集合中的對象個數即可

提交結果:

class Solution {
    static String[] s={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
    public  int uniqueMorseRepresentations(String[] words) {
        Set<String> result=new HashSet<>();
        for (String word:words) {
            result.add(getString(word));
        }
        return result.size();
    }
    public  String getString(String word){
        StringBuilder sb=new StringBuilder();
        for(char x:word.toCharArray()){
            sb.append(s[x-'a']);
        }
        return sb.toString();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章