804. Unique Morse Code Words

题目链接:

https://leetcode.com/problems/unique-morse-code-words/description/

解法一:

  • trans将一个字母转换为一个摩斯码,其中ord函数返回字母的ASCII码;
  • map_word将一个单词里面的所有字母转换为摩斯码
class Solution(object):
    def uniqueMorseRepresentations(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        moorse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        trans = lambda x: moorse[ord(x) - ord('a')]
        #这里map_word定义的是一个函数
        map_word = lambda word: ''.join([trans(x) for x in word])
        #map将words里的每个单词进行map_word操作
        res = map(map_word, words)
        return len(set(res))

解法二:

  • 本质相同,没有使用库函数更容易理解
class Solution(object):
    def uniqueMorseRepresentations(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        MORSE = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
                 "....", "..", ".---", "-.-", ".-..", "--", "-.",
                 "---", ".--.", "--.-", ".-.", "...", "-", "..-",
                 "...-", ".--", "-..-", "-.--", "--.."]

        lookup = {"".join(MORSE[ord(c) - ord('a')] for c in word) \
                  for word in words}
        return len(lookup)

你可能感兴趣的:(804. Unique Morse Code Words)