leetcode刷题总结 python版随笔-生活工作点滴

leetcode 804. Unique Morse Code

2019-07-10  本文已影响0人  PJCK

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)

这个代码涉及到的知识点:

最后的解释:

上一篇下一篇

猜你喜欢

热点阅读