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.
這個(gè)題很簡(jiǎn)單。就是通過(guò)建立一個(gè)哈希表昔穴,然后建立一個(gè)集合镰官,把字符串對(duì)應(yīng)的編碼組成字符串,充入集合吗货,統(tǒng)計(jì)集合的長(zhǎng)度就行泳唠。
不過(guò),官網(wǎng)上的Python代碼我覺(jué)得很巧妙宙搬,同時(shí)也讓我發(fā)現(xiàn)自己的python的基礎(chǔ)的不足笨腥。因此我在此寫總結(jié),以此鞏固基礎(chǔ)勇垛。
Python代碼(官網(wǎng)):
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
Morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---",
"-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-",
"...-",".--","-..-","-.--","--.."]
seen = {"".join(Morse[ord(c) - ord('a')] for c in word) for word in words}
return len(seen)
這個(gè)代碼涉及到的知識(shí)點(diǎn):
- 集合脖母,在Python中,集合可以用大括號(hào)或set()建立和表示闲孤。
- 集合生成式谆级,這個(gè)集合生成式和列表生成式比較類似只不過(guò)集合生成式最后得到的是一個(gè)無(wú)序的集合。
- join()函數(shù)讼积,str.join()中官方文檔的說(shuō)明:
Return a string which is the concatenation of the strings in iterable. ATypeError
will be raised if there are any non-string values in iterable, includingbytes
objects. The separator between elements is the string providing this method.
即指的是返回一個(gè)由迭代器里面的字符串連接部分的字符串肥照,并且提供這個(gè)方法的字符串會(huì)作為元素之間的間隔。 - ord() 勤众,它是chr()的配對(duì)的函數(shù)舆绎,返回字符的對(duì)應(yīng)的ASCII值或Unicode值。
最后的解釋:
- "".join(Morse[ord(c) - ord('a')] for c in word) 返回單詞里面的每個(gè)字符的對(duì)應(yīng)的ASCII值減去‘a(chǎn)’對(duì)應(yīng)的ASCII值们颜,根據(jù)這個(gè)數(shù)在預(yù)定的Morse列表中選取相應(yīng)的編碼吕朵,組成一個(gè)字符串。
- A for word in words 就是在words中遍歷掌桩,得到word單詞边锁。
- len(seen) seen是一個(gè)無(wú)序的集合,可以用len()函數(shù)統(tǒng)計(jì)其長(zhǎng)度波岛。