美文网首页
804. Unique Morse Code Words

804. Unique Morse Code Words

作者: Harry_da0d | 来源:发表于2018-06-06 19:18 被阅读0次

    题目链接:

    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

          本文链接:https://www.haomeiwen.com/subject/bbrisftx.html