LeetCode 804 - Unique Morse Code Words (Coding With C#)

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 "--...--.".

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.

 

基本上題目,就是叫我們做字串對照的轉換,就一般來說常用在密碼學上。

要做到以下:

  1. 輸入一字串
  2. 將字串轉換成對應的樣本型態
  3. 輸出轉換後有幾個相同的字串

我實作後的程式碼如下:

public static int UniqueMorseRepresentations(string[] words)
{
   string[] mapstring = new string[] { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };

   var InpuArrayLength = words.Count();
   HashSet<string> encodingHashset = new HashSet<string>();

   for (int i = 0; i <= InpuArrayLength - 1; i++)
   {
       var WordLength = words[i].Length;
       string TempString = "";

       for (int x = 0; x <= WordLength - 1; x++)
       {
         var wordASCII = Convert.ToInt32(words[i][x]);
         var wordnum = wordASCII - 97 ;
         TempString = TempString + mapstring[wordnum];
       }

         encodingHashset.Add(TempString);
   }

  return encodingHashset.Count();
}

解釋:

這邊用到的兩個迴圈,一個跑的是陣列有幾個,另一個是做字串轉換。

將字母取出,轉換成ASCII編碼後再減去最小值的'a'的ASCII編碼得到就會是相對應的樣本陣列位子。

最後使用  HashSet<T> 類別來做為儲存,因為他可以排除掉重複值的儲存。

最後再回傳有幾個就完成了。