leetcode 804. Unique Morse Code
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.
这个题很简单。就是通过建立一个哈希表,然后建立一个集合,把字符串对应的编码组成字符串,充入集合,统计集合的长度就行。
不过,官网上的Python代码我觉得很巧妙,同时也让我发现自己的python的基础的不足。因此我在此写总结,以此巩固基础。
Python代码(官网):
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)
这个代码涉及到的知识点:
- 集合,在Python中,集合可以用大括号或set()建立和表示。
- 集合生成式,这个集合生成式和列表生成式比较类似只不过集合生成式最后得到的是一个无序的集合。
- join()函数,str.join()中官方文档的说明:
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.
即指的是返回一个由迭代器里面的字符串连接部分的字符串,并且提供这个方法的字符串会作为元素之间的间隔。 - ord() ,它是chr()的配对的函数,返回字符的对应的ASCII值或Unicode值。
最后的解释:
- "".join(Morse[ord(c) - ord('a')] for c in word) 返回单词里面的每个字符的对应的ASCII值减去‘a’对应的ASCII值,根据这个数在预定的Morse列表中选取相应的编码,组成一个字符串。
- A for word in words 就是在words中遍历,得到word单词。
- len(seen) seen是一个无序的集合,可以用len()函数统计其长度。