1. 程式人生 > >Leetcode804.Unique Morse Code Words (莫爾斯電碼重複)

Leetcode804.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]只包含小寫字母。
public class Solution {
	 public int uniqueMorseRepresentations(String[] words) {
	        String[] codes = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
	        TreeSet<String> set = new TreeSet<>();
	        for(String word: words){
	            StringBuilder res = new StringBuilder();
	            for(int i = 0 ; i < word.length() ; i ++)
	                res.append(codes[word.charAt(i) - 'a']);
	            set.add(res.toString());
	        }
	        return set.size();
	    }
}

測試程式碼

public class Test {
	public static void main(String[] args) {
		String[] a = { "gin", "zen", "gig", "msg" };
		Solution solution = new Solution();
		System.out.println(solution.uniqueMorseRepresentations(a));
	}
}

 執行結果